import 'dart:async';
import 'dart:ui' as ui;

import 'package:collection/collection.dart';
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/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.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/todo_section/models/resp_models/ancillary_order_list_response_model.dart';
import 'package:hmg_patient_app_new/features/todo_section/models/resp_models/ancillary_order_procedures_detail_response_model.dart';
import 'package:hmg_patient_app_new/features/todo_section/todo_section_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/todo_section/ancillary_order_payment_page.dart';
import 'package:hmg_patient_app_new/presentation/todo_section/widgets/ancillary_orders_list.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/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

class AncillaryOrderDetailsList extends StatefulWidget {
  final int appointmentNoVida;
  final int orderNo;
  final int projectID;
  final String projectName;
  final String setupID;

  const AncillaryOrderDetailsList({
    super.key,
    required this.appointmentNoVida,
    required this.orderNo,
    required this.projectID,
    required this.projectName,
    required this.setupID,
  });

  @override
  State<AncillaryOrderDetailsList> createState() => _AncillaryOrderDetailsListState();
}

class _AncillaryOrderDetailsListState extends State<AncillaryOrderDetailsList> {
  late TodoSectionViewModel todoSectionViewModel;
  late AppState appState;
  List<AncillaryOrderProcDetail> selectedProcedures = [];

  @override
  void initState() {
    super.initState();
    appState = getIt.get<AppState>();
    todoSectionViewModel = context.read<TodoSectionViewModel>();
    scheduleMicrotask(() async {
      await todoSectionViewModel.getPatientOnlineAncillaryOrderDetailsProceduresList(
        appointmentNoVida: widget.appointmentNoVida,
        orderNo: widget.orderNo,
        projectID: widget.projectID,
        onSuccess: (response) {
          _autoSelectEligibleProcedures();
        },
      );
    });
  }

  void _autoSelectEligibleProcedures() {
    if (!mounted) return;
    selectedProcedures.clear();
    if (todoSectionViewModel.patientAncillaryOrderProceduresList.isNotEmpty) {
      final procedures = todoSectionViewModel.patientAncillaryOrderProceduresList[0].ancillaryOrderProcDetailsList;
      if (procedures != null) {
        for (var proc in procedures) {
          if (!_isProcedureDisabled(proc)) {
            selectedProcedures.add(proc);
          }
        }
      }
    }
    if (mounted) setState(() {});
  }

  bool _isProcedureDisabled(AncillaryOrderProcDetail procedure) {
    // return true;
    return (procedure.isApprovalRequired == true && procedure.isApprovalCreated == false) ||
        (procedure.isApprovalCreated == true && procedure.approvalNo == 0) ||
        (procedure.isApprovalRequired == true && procedure.isApprovalCreated == true && procedure.approvalNo == 0);
  }

  bool _isProcedureSelected(AncillaryOrderProcDetail procedure) {
    return selectedProcedures.contains(procedure);
  }

  void _toggleProcedureSelection(AncillaryOrderProcDetail procedure) {
    setState(() {
      if (_isProcedureSelected(procedure)) {
        selectedProcedures.remove(procedure);
      } else {
        selectedProcedures.add(procedure);
      }
    });
  }

  String _getApprovalStatusText(AncillaryOrderProcDetail procedure) {
    if (procedure.isApprovalRequired == false) {
      return LocaleKeys.cash.tr(context: context);
    } else {
      if (procedure.isApprovalCreated == true && procedure.approvalNo != 0) {
        return LocaleKeys.approved.tr(context: context);
      } else if (procedure.isApprovalRequired == true && procedure.isApprovalCreated == true && procedure.approvalNo == 0) {
        return LocaleKeys.approvalRejectedPleaseVisitReceptionist.tr(context: context);
      } else {
        return LocaleKeys.sentForApproval.tr(context: context);
      }
    }
  }

  num _getTotalAmount() {
    num total = 0.0;
    for (var proc in selectedProcedures) {
      total += (proc.patientShareWithTax ?? 0);
    }
    return total;
    // return 1234.50;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<TodoSectionViewModel>(builder: (context, viewModel, child) {
        AncillaryOrderProcedureItem? orderData;
        if (viewModel.patientAncillaryOrderProceduresList.isNotEmpty) {
          orderData = viewModel.patientAncillaryOrderProceduresList[0];
        }
        return Column(
          children: [
            Expanded(
              child: CollapsingListView(
                title: LocaleKeys.ancillaryOrderDetails.tr(context: context),
                child: viewModel.isAncillaryDetailsProceduresLoading
                    ? _buildLoadingShimmer().paddingSymmetrical(24.w, 0)
                    : viewModel.patientAncillaryOrderProceduresList.isEmpty
                        ? _buildDefaultEmptyState(context).paddingSymmetrical(24.w, 0)
                        : SingleChildScrollView(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                SizedBox(height: 16.h),
                                if (orderData != null) _buildPatientInfoCard(orderData),
                                SizedBox(height: 16.h),
                                if (orderData != null) _buildProceduresSection(orderData),
                              ],
                            ).paddingSymmetrical(24.w, 0),
                          ),
              ),
            ),
            if (orderData != null && !viewModel.isAncillaryDetailsProceduresLoading) _buildStickyPaymentButton(orderData),
          ],
        );
      }),
    );
  }

  Widget _buildLoadingShimmer() {
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.zero,
      itemCount: 3,
      itemBuilder: (context, index) {
        return AncillaryOrderCard(
          order: AncillaryOrderItem(),
          isLoading: true,
        );
      },
    );
  }

  Widget _buildDefaultEmptyState(BuildContext context) {
    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.noProceduresAvailableForSelectedOrder.tr(context: context),
            isSmallWidget: true,
            width: 62.w,
            height: 62.h,
          ),
        ),
      ),
    );
  }

  Widget _buildPatientInfoCard(AncillaryOrderProcedureItem orderData) {
    final user = appState.getAuthenticatedUser();
    final patientName = orderData.patientName ?? user?.firstName ?? "N/A";
    final patientMRN = orderData.patientID ?? user?.patientId;
    final nationalID = user?.patientIdentificationNo ?? "";

    // Determine gender for profile image (assuming 1 = male, 2 = female)
    final gender = user?.gender ?? 1;

    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: true,
      ),
      child: Column(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Header Row with Profile Image, Name, and QR Code
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Utils.buildImgWithAssets(
                    icon: gender == 1 ? AppAssets.maleImg : AppAssets.femaleImg,
                    width: 56.w,
                    height: 56.h,
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        patientName.toText18(
                          isBold: true,
                          weight: FontWeight.w600,
                          textOverflow: TextOverflow.ellipsis,
                          maxlines: 2,
                        ),
                      ],
                    ),
                  ),
                ],
              ),

              SizedBox(height: 12.h),

              Wrap(
                alignment: WrapAlignment.start,
                spacing: 4.w,
                runSpacing: 4.h,
                children: [
                  AppCustomChipWidget(
                    // icon: AppAssets.file_icon,
                    labelText: "${LocaleKeys.fileno.tr(context: context)}: ${patientMRN ?? 'N/A'}",
                    iconSize: 12.w,
                    isEnglishOnly: true,
                  ),

                  // National ID
                  if (nationalID.isNotEmpty)
                    AppCustomChipWidget(
                      // icon: AppAssets.card_user,
                      labelText: "ID: $nationalID",
                      iconSize: 12.w,
                      isEnglishOnly: true,
                    ),

                  // Appointment Number
                  if (orderData.appointmentNo != null)
                    AppCustomChipWidget(
                      // icon: AppAssets.calendar,
                      labelText: "${LocaleKeys.appointment.tr(context: context)}: ${orderData.appointmentNo}",
                      iconSize: 12.w,
                      isEnglishOnly: true,
                    ),

                  // Order Number
                  if (orderData.ancillaryOrderProcDetailsList?.firstOrNull?.orderNo != null)
                    AppCustomChipWidget(
                      labelText: "Order #: ${orderData.ancillaryOrderProcDetailsList!.first.orderNo}",
                      isEnglishOnly: true,
                    ),

                  // Blood Group
                  if (user?.bloodGroup != null && user!.bloodGroup!.isNotEmpty)
                    AppCustomChipWidget(
                      // icon: AppAssets.blood_icon,
                      labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 8.w),
                      labelText: "Blood: ${user.bloodGroup}",
                      iconColor: AppColors.primaryRedColor,
                    ),

                  // Insurance Company (if applicable)
                  if (orderData.companyName != null && orderData.companyName!.isNotEmpty)
                    AppCustomChipWidget(
                      icon: AppAssets.insurance_active_icon,
                      labelText: orderData.companyName!,
                      iconColor: AppColors.successColor,
                      backgroundColor: AppColors.successColor.withValues(alpha: 0.15),
                      iconSize: 12.w,
                      labelPadding: EdgeInsetsDirectional.only(start: -6.w, end: 8.w),
                      isEnglishOnly: true,
                    ),

                  // Policy Number
                  if (orderData.insurancePolicyNo != null && orderData.insurancePolicyNo!.isNotEmpty)
                    AppCustomChipWidget(
                      labelText: "${LocaleKeys.policyNumber.tr(context: context)}: ${orderData.insurancePolicyNo}",
                      isEnglishOnly: true,
                    ),

                  AppCustomChipWidget(
                    labelText: "Doctor: ${orderData.doctorName ?? "N/A"}",
                  ),
                  if (widget.projectName.isNotEmpty)
                    AppCustomChipWidget(
                      labelText: widget.projectName,
                    ),
                  if (orderData.clinicName != null && orderData.clinicName!.isNotEmpty)
                    AppCustomChipWidget(
                      labelText: "Clinic: ${orderData.clinicName!}",
                    ),
                  if (orderData.clinicName != null && orderData.clinicName!.isNotEmpty)
                    Directionality(
                      textDirection: ui.TextDirection.ltr,
                      child: AppCustomChipWidget(
                        labelText: "${LocaleKeys.date.tr(context: context)}: ${DateFormat('MMM dd yyyy').format(orderData.appointmentDate!)}",
                        isEnglishOnly: true,
                      ),
                    ),
                ],
              ),

              // SizedBox(height: 12.h),
              //
              // // Additional Details Section
              // Container(
              //   padding: EdgeInsets.all(12.h),
              //   decoration: BoxDecoration(
              //     color: AppColors.bgScaffoldColor,
              //     borderRadius: BorderRadius.circular(12.r),
              //   ),
              //   child: Column(
              //     children: [
              //       _buildInfoRow(
              //         "Doctor".needTranslation,
              //         orderData.doctorName ?? "N/A",
              //       ),
              //       if (orderData.clinicName != null && orderData.clinicName!.isNotEmpty)
              //         _buildInfoRow(
              //           "Clinic".needTranslation,
              //           orderData.clinicName!,
              //         ),
              //       if (orderData.appointmentDate != null)
              //         _buildInfoRow(
              //           "Appointment Date".needTranslation,
              //           DateFormat('MMM dd, yyyy').format(orderData.appointmentDate!),
              //         ),
              //     ],
              //   ),
              // ),
            ],
          ).paddingOnly(top: 16.h, right: 16.w, left: 16.w, bottom: 12.h),

          // Divider
          Container(height: 1, color: AppColors.dividerColor),

          // Summary Section
        ],
      ),
    );
  }

  Widget _buildSummarySection(AncillaryOrderProcedureItem orderData) {
    final totalProcedures = orderData.ancillaryOrderProcDetailsList?.length ?? 0;
    final selectedCount = selectedProcedures.length;

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            LocaleKeys.procedures.tr(context: context).toText12(
                  color: AppColors.textColorLight,
                  isBold: true,
                ),
            "$selectedCount of $totalProcedures selected".toText14(
              isBold: true,
              weight: FontWeight.bold,
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            LocaleKeys.totalAmount.tr(context: context).toText12(
                  color: AppColors.textColorLight,
                  isBold: true,
                ),
            Row(
              children: [
                Utils.getPaymentAmountWithSymbol(
                  _getTotalAmount().toStringAsFixed(2).toText14(
                        isBold: true,
                        weight: FontWeight.bold,
                        color: AppColors.primaryRedColor,
                      ),
                  AppColors.textColorLight,
                  13,
                  isSaudiCurrency: true,
                ),
                //
                // _getTotalAmount().toStringAsFixed(2).toText14(
                //       isBold: true,
                //       weight: FontWeight.bold,
                //       color: AppColors.primaryRedColor,
                //     ),
                // SizedBox(width: 4.w),
                // "SAR".toText12(color: AppColors.textColorLight),
              ],
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.only(bottom: 8.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            flex: 2,
            child: "$label:".toText12(color: AppColors.textColorLight, isBold: true),
          ),
          SizedBox(width: 8.w),
          Expanded(
            flex: 3,
            child: value.toText12(color: AppColors.textColor, isBold: true),
          ),
        ],
      ),
    );
  }

  Widget _buildProceduresSection(AncillaryOrderProcedureItem orderData) {
    if (orderData.ancillaryOrderProcDetailsList == null || orderData.ancillaryOrderProcDetailsList!.isEmpty) {
      return SizedBox.shrink();
    }

    // Group procedures by category
    final groupedProcedures = groupBy(
      orderData.ancillaryOrderProcDetailsList!,
      (AncillaryOrderProcDetail proc) => proc.procedureCategoryName ?? "Other",
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: groupedProcedures.entries.map((entry) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            entry.key.toText18(isBold: true),
            SizedBox(height: 12.h),
            ...entry.value.map((procedure) => _buildProcedureCard(procedure)),
            SizedBox(height: 16.h),
          ],
        );
      }).toList(),
    );
  }

  Widget _buildProcedureCard(AncillaryOrderProcDetail procedure) {
    final isDisabled = _isProcedureDisabled(procedure);
    // final isDisabled = _isProcedureDisabled(procedure);
    final isSelected = _isProcedureSelected(procedure);

    return AnimationConfiguration.staggeredList(
        position: 0,
        duration: const Duration(milliseconds: 500),
        child: SlideAnimation(
          verticalOffset: 100.0,
          child: FadeInAnimation(
            child: AnimatedContainer(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
              margin: EdgeInsets.only(bottom: 12.h),
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: isDisabled ? AppColors.greyColor : AppColors.whiteColor,
                borderRadius: 24.h,
                hasShadow: !isDisabled,
              ),
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: isDisabled ? null : () => _toggleProcedureSelection(procedure),
                  borderRadius: BorderRadius.circular(24.h),
                  child: Container(
                    padding: EdgeInsets.all(14.h),
                    decoration: BoxDecoration(borderRadius: BorderRadius.circular(24.h)),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if (!isDisabled)
                              Padding(
                                padding: EdgeInsets.only(right: 8.w),
                                child: Checkbox(
                                  value: isSelected,
                                  onChanged: (v) => _toggleProcedureSelection(procedure),
                                  activeColor: AppColors.primaryRedColor,
                                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                  visualDensity: VisualDensity.compact,
                                ),
                              ),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  (procedure.procedureName ?? "N/A").toText14(isBold: true, maxlines: 2),
                                ],
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 8.h),
                        Wrap(
                          direction: Axis.horizontal,
                          spacing: 3.h,
                          runSpacing: 8.h,
                          children: [
                            AppCustomChipWidget(
                              labelText: _getApprovalStatusText(procedure),
                              // backgroundColor: ,
                            ),
                            // if (procedure.procedureID != null)
                            //   AppCustomChipWidget(
                            //     labelText: "ID: ${procedure.procedureID}",
                            //   ),
                            if (procedure.isCovered == true)
                              AppCustomChipWidget(
                                labelText: LocaleKeys.covered.tr(context: context),
                                backgroundColor: AppColors.successColor.withValues(alpha: 0.1),
                                textColor: AppColors.successColor,
                              ),
                          ],
                        ),
                        SizedBox(height: 12.h),
                        Container(height: 1, color: AppColors.dividerColor),
                        SizedBox(height: 12.h),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  LocaleKeys.price.tr(context: context).toText10(color: AppColors.textColorLight),
                                  SizedBox(height: 4.h),
                                  Row(
                                    children: [
                                      Utils.getPaymentAmountWithSymbol(
                                        (procedure.patientShare ?? 0).toStringAsFixed(2).toText14(isBold: true, isEnglishOnly: true),
                                        AppColors.textColorLight,
                                        13,
                                        isSaudiCurrency: true,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  LocaleKeys.vatPercent.tr(context: context).toText10(color: AppColors.textColorLight),
                                  SizedBox(height: 4.h),
                                  Row(
                                    children: [
                                      Utils.getPaymentAmountWithSymbol(
                                        (procedure.patientTaxAmount ?? 0).toStringAsFixed(2).toText12(isBold: true, isEnglishOnly: true),
                                        AppColors.textColorLight,
                                        13,
                                        isSaudiCurrency: true,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  LocaleKeys.total.tr(context: context).toText10(color: AppColors.textColorLight),
                                  SizedBox(height: 4.h),
                                  Row(
                                    children: [
                                      Utils.getPaymentAmountWithSymbol(
                                        (procedure.patientShareWithTax ?? 0).toStringAsFixed(2).toText12(isBold: true, isEnglishOnly: true),
                                        AppColors.textColorLight,
                                        13,
                                        isSaudiCurrency: true,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ));
  }

  Widget _buildStickyPaymentButton(orderData) {
    final isButtonEnabled = selectedProcedures.isNotEmpty;
    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.r,
        hasShadow: true,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 4.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(child: LocaleKeys.upcomingPaymentNow.tr(context: context).toText12(isBold: true, color: AppColors.greyTextColor)),
            ],
          ),
          SizedBox(height: 18.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(
                width: isFoldable ? 220.w : 200.w,
                child: Utils.getPaymentMethods(),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Utils.getPaymentAmountWithSymbol(
                      NumberFormat.decimalPattern().format(_getTotalAmount()).toText24(isBold: true, isEnglishOnly: true), AppColors.blackColor, 17,
                      isSaudiCurrency: true),
                ],
              ),
            ],
          ),
          SizedBox(height: 16.h),
          CustomButton(
            borderWidth: 0,
            backgroundColor: AppColors.infoLightColor,
            text: LocaleKeys.proceedToPayment.tr(context: context),
            onPressed: () {
              // Navigate to payment page with selected procedures
              todoSectionViewModel.setIsAncillaryOrdersNeedReloading(true);
              Navigator.of(context).push(
                CustomPageRoute(
                  page: AncillaryOrderPaymentPage(
                    appointmentNoVida: widget.appointmentNoVida,
                    orderNo: widget.orderNo,
                    projectID: widget.projectID,
                    selectedProcedures: selectedProcedures,
                    totalAmount: _getTotalAmount(),
                    appointmentDate: orderData.appointmentDate,
                    setupID: widget.setupID,
                  ),
                ),
              );
            },
            isDisabled: !isButtonEnabled,
            textColor: Colors.white,
            borderRadius: 12.r,
            borderColor: Colors.transparent,
            padding: EdgeInsets.symmetric(vertical: 16.h),
          ),
          SizedBox(height: 22.h),
        ],
      ).paddingOnly(left: 16.h, top: 24.h, right: 16.h, bottom: 0.h),
    );
  }
}
