import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/hmg_services/hmg_services_view_model.dart';
import 'package:hmg_patient_app_new/features/hmg_services/models/resq_models/get_cmc_all_orders_resp_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:provider/provider.dart';

class HhcOrderDetailPage extends StatefulWidget {
  const HhcOrderDetailPage({super.key});

  @override
  State<HhcOrderDetailPage> createState() => _HhcOrderDetailPageState();
}

class _HhcOrderDetailPageState extends State<HhcOrderDetailPage> {
  @override
  void initState() {
    super.initState();
    final hmgServicesViewModel = context.read<HmgServicesViewModel>();
    scheduleMicrotask(() async {
      await hmgServicesViewModel.getAllHhcOrders();
    });
  }

  Color _getStatusColor(int? statusId) {
    switch (statusId) {
      case 1: // Pending
        return const Color(0xffCC9B14);
      case 2: // Processing
        return const Color(0xff2E303A);
      case 3: // Completed
        return const Color(0xff359846);
      case 4: // Cancelled
      case 6: // Rejected
      case 7: // Rejected
        return const Color(0xffD02127);
      default:
        return AppColors.greyColor;
    }
  }

  String _formatDate(String? dateString) {
    if (dateString == null) return '';
    try {
      final date = DateTime.parse(dateString);
      return DateFormat('MMM dd, yyyy').format(date);
    } catch (e) {
      return dateString;
    }
  }

  Widget _buildLoadingShimmer() {
    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: 3,
      separatorBuilder: (_, __) => SizedBox(height: 12.h),
      itemBuilder: (context, index) {
        return _buildOrderCard(GetCMCAllOrdersResponseModel(), isLoading: true);
      },
    );
  }

  Widget _buildOrderCard(GetCMCAllOrdersResponseModel order, {bool isLoading = false}) {
    final statusColor = _getStatusColor(order.statusId);

    return AnimatedContainer(
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInOut,
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: true,
      ),
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Status and Date Row
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                  decoration: BoxDecoration(
                    color: statusColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: (isLoading ? "Processing" : order.statusText ?? '')
                      .toText12(
                        color: statusColor,
                        isBold: true,
                      )
                      .toShimmer2(isShow: isLoading),
                ),
                SizedBox(width: 8.w),
                (isLoading ? "Jan 15, 2024" : _formatDate(order.created))
                    .toText12(
                      color: AppColors.textColorLight,
                      isBold: true,
                    )
                    .toShimmer2(isShow: isLoading),
              ],
            ),

            SizedBox(height: 16.h),

            // Request ID
            Row(
              children: [
                if (!isLoading) ...[
                  LocaleKeys.requestID.tr(context: context).toText14(
                        color: AppColors.textColorLight,
                        weight: FontWeight.w600,
                      ),
                  SizedBox(width: 4.w),
                ],
                (isLoading ? "12345" : "${order.iD ?? '-'}").toText16(isBold: true).toShimmer2(isShow: isLoading),
              ],
            ),

            SizedBox(height: 12.h),

            // Chips for Hospital, Service, and Amount
            Wrap(
              spacing: 6.w,
              runSpacing: 6.h,
              children: [
                // Service
                if (order.serviceText != null || isLoading)
                  AppCustomChipWidget(
                    icon: AppAssets.servicesBottom,
                    labelText: isLoading ? "Service Name" : order.serviceText ?? '-',
                  ).toShimmer2(isShow: isLoading),
              ],
            ),

            // // Cancel Button
            // if (canCancel || isLoading) ...[
            //   SizedBox(height: 16.h),
            //   Row(
            //     children: [
            //       Expanded(
            //         child: CustomButton(
            //           text: "Cancel Order".needTranslation,
            //           onPressed: isLoading ? () {} : () => HhcUiSelectionHelper.showCancelConfirmationDialog(context: context, order: order),
            //           backgroundColor: AppColors.primaryRedColor,
            //           borderColor: AppColors.primaryRedColor,
            //           textColor: AppColors.whiteColor,
            //           fontSize: 14.f,
            //           isBold: true,
            //           borderRadius: 10.r,
            //           height: 44.h,
            //         ).toShimmer2(isShow: isLoading),
            //       ),
            //     ],
            //   ),
            // ]
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 40.h),
        child: Container(
          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
            color: AppColors.whiteColor,
            borderRadius: 12.r,
            hasShadow: false,
          ),
          child: Utils.getNoDataWidget(
            context,
            noDataText: LocaleKeys.dontHaveHHCOrders.tr(context: context),
            isSmallWidget: true,
            width: 62.w,
            height: 62.h,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CollapsingListView(
      title: LocaleKeys.hhcOrders.tr(context: context),
      isLeading: true,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Consumer<HmgServicesViewModel>(
              builder: (context, viewModel, child) {
                if (viewModel.isHhcOrdersLoading) {
                  return _buildLoadingShimmer();
                }

                if (viewModel.hhcOrdersList.isEmpty) {
                  return _buildEmptyState();
                }

                return ListView.separated(
                  padding: EdgeInsets.only(top: 24.h),
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: viewModel.hhcOrdersList.length,
                  separatorBuilder: (_, __) => SizedBox(height: 12.h),
                  itemBuilder: (context, index) {
                    final order = viewModel.hhcOrdersList.reversed.toList()[index];

                    return AnimationConfiguration.staggeredList(
                      position: index,
                      duration: const Duration(milliseconds: 500),
                      child: SlideAnimation(
                        verticalOffset: 100.0,
                        child: FadeInAnimation(
                          child: _buildOrderCard(order),
                        ),
                      ),
                    );
                  },
                );
              },
            ),
          ],
        ).paddingSymmetrical(24.w, 0),
      ),
    );
  }
}
