import 'dart:async';
import 'dart:developer';
import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/cache_consts.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/core/utils/date_util.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/payfort/models/apple_pay_request_insert_model.dart';
import 'package:hmg_patient_app_new/features/payfort/payfort_view_model.dart';
import 'package:hmg_patient_app_new/features/paytabs/models/paytabs_transaction_response_model.dart';
import 'package:hmg_patient_app_new/features/paytabs/paytabs_view_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/home/navigation_screen.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/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/in_app_browser/InAppBrowser.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

class AncillaryOrderPaymentPage extends StatefulWidget {
  final DateTime? appointmentDate;
  final int appointmentNoVida;
  final int orderNo;
  final int projectID;
  final String setupID;
  final List<AncillaryOrderProcDetail> selectedProcedures;
  final num totalAmount;

  const AncillaryOrderPaymentPage({
    super.key,
    required this.appointmentDate,
    required this.appointmentNoVida,
    required this.orderNo,
    required this.projectID,
    required this.setupID,
    required this.selectedProcedures,
    required this.totalAmount,
  });

  @override
  State<AncillaryOrderPaymentPage> createState() => _AncillaryOrderPaymentPageState();
}

class _AncillaryOrderPaymentPageState extends State<AncillaryOrderPaymentPage> {
  late PayfortViewModel payfortViewModel;
  late AppState appState;
  late TodoSectionViewModel todoSectionViewModel;
  late PayTabsViewModel paytabsViewModel;

  MyInAppBrowser? browser;
  String selectedPaymentMethod = "";
  String transID = "";

  @override
  void initState() {
    scheduleMicrotask(() {
      payfortViewModel.initPayfortViewModel();
      payfortViewModel.setIsApplePayConfigurationLoading(false);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    appState = getIt.get<AppState>();
    todoSectionViewModel = Provider.of<TodoSectionViewModel>(context);
    payfortViewModel = Provider.of<PayfortViewModel>(context);
    paytabsViewModel = Provider.of<PayTabsViewModel>(context, listen: false);

    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Consumer<TodoSectionViewModel>(
        builder: (context, todoVM, child) {
          return Column(
            children: [
              Expanded(
                child: CollapsingListView(
                  title: LocaleKeys.selectPaymentMethod.tr(context: context),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(height: 24.h),

                        // Mada Payment Option
                        Container(
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            color: AppColors.whiteColor,
                            borderRadius: 20.h,
                            hasShadow: false,
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Utils.buildImgWithAssets(icon: AppAssets.mada, width: 80.h, height: 30.h, fit: BoxFit.contain),
                                  SizedBox(height: 16.h),
                                  LocaleKeys.mada.tr(context: context).toText16(isBold: true).toShimmer2(isShow: todoVM.isProcessingPayment),
                                ],
                              ),
                              SizedBox(width: 8.h),
                              const Spacer(),
                              Transform.flip(
                                flipX: appState.isArabic(),
                                child: Utils.buildSvgWithAssets(
                                  icon: AppAssets.forward_arrow_icon_small,
                                  iconColor: AppColors.blackColor,
                                  width: 18.h,
                                  height: 13.h,
                                  fit: BoxFit.contain,
                                ).toShimmer2(isShow: todoVM.isProcessingPayment),
                              ),
                            ],
                          ).paddingSymmetrical(16.h, 16.h),
                        ).paddingSymmetrical(24.h, 0.h).onPress(() async {
                          if (!todoVM.isProcessingPayment) {
                            selectedPaymentMethod = "MADA";
                            if (appState.isPaytabsEnabled) {
                              transID = Utils.getAdvancePaymentTransID(
                                widget.projectID,
                                appState.getAuthenticatedUser()!.patientId!,
                              );
                              paytabsViewModel.setPaymentConfiguration(
                                "Ancillary Orders Payment",
                                widget.totalAmount,
                              );
                              paytabsViewModel.startCardPayment(
                                  paymentOption: selectedPaymentMethod,
                                  liveServiceID: "0",
                                  isScheduleLiveCare: "false",
                                  appointmentDate: DateUtil.convertDateToString(DateTime.now()),
                                  appointmentNo: "0",
                                  doctorID: "0",
                                  transactionID: transID,
                                  amount: widget.totalAmount.toString(),
                                  fileNumber: appState.getAuthenticatedUser()!.patientId!.toString(),
                                  orderDescription: "Ancillary Orders Payment",
                                  serviceID: ServiceTypeEnum.advancePayment.getIdFromServiceEnum().toString(),
                                  projectID: widget.projectID.toString(),
                                  onSuccess: (PaytabsTransactionResponseModel transactionData) async {
                                    final paymentAmount = widget.totalAmount;
                                final fortId = transactionData.transactionReference;
                                final paymentMethod = selectedPaymentMethod;

                                // Call createAdvancePayment with the payment details
                                _createAdvancePayment(
                                  paymentAmount: paymentAmount.toDouble(),
                                  paymentReference: fortId!,
                                  paymentMethod: paymentMethod,
                                );
                              }, onError: (err) {
                                showCommonBottomSheetWithoutHeight(
                                  context,
                                  child: Utils.getErrorWidget(loadingText: err.toString()),
                                  callBackFunc: () {},
                                  isFullScreen: false,
                                  isCloseButtonVisible: true,
                                );
                              });
                            } else {
                              if (appState.isPayfortHostedPageEnabled) {
                                LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPaymentInformation.tr(context: context));
                                transID = Utils.getAdvancePaymentTransID(
                                  widget.projectID,
                                  appState.getAuthenticatedUser()!.patientId!,
                                );

                                await payfortViewModel.getPayfortConfigurations(
                                  serviceId: ServiceTypeEnum.ancillaryOrder.getIdFromServiceEnum(),
                                  projectId: widget.projectID,
                                  integrationId: 1,
                                );

                                payfortViewModel.initiatePaymentWithCard(
                                  "mada",
                                  "0",
                                  "false",
                                  DateUtil.convertDateToString(DateTime.now()),
                                  "0",
                                  "0",
                                  transactionID: transID,
                                  fileNumber: appState.getAuthenticatedUser()!.patientId.toString(),
                                  amount: widget.totalAmount.toString(),
                                  orderDescription: "Ancillary Order Payment",
                                  onSucceeded: (paymentResult) async {
                                    print("Payment Success Data: ${paymentResult.toString()}");
                                    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingPaymentStatusPleaseWait.tr(context: context));

                                    // Call createAdvancePayment with the payment details
                                    _createAdvancePayment(
                                      paymentAmount: widget.totalAmount,
                                      paymentReference: paymentResult.fortId!,
                                      paymentMethod: selectedPaymentMethod,
                                    );
                                  },
                                  onFailed: (err) {
                                    print("Payment Failed Data: ${err.toString()}");
                                    showCommonBottomSheetWithoutHeight(
                                      context,
                                      child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
                                      callBackFunc: () {},
                                      isFullScreen: false,
                                      isCloseButtonVisible: true,
                                    );
                                  },
                                );
                              } else {
                                _openPaymentURL("mada");
                              }
                            }
                          }
                        }),

                        SizedBox(height: 16.h),

                        // Visa/Mastercard Payment Option
                        Container(
                          decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                            color: AppColors.whiteColor,
                            borderRadius: 20.h,
                            hasShadow: false,
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.max,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Utils.buildImgWithAssets(icon: AppAssets.visa, width: 50.h, height: 50.h),
                                      SizedBox(width: 8.h),
                                      Utils.buildImgWithAssets(icon: AppAssets.mastercard, width: 40.h, height: 40.h, fit: BoxFit.contain),
                                    ],
                                  ).toShimmer2(isShow: todoVM.isProcessingPayment),
                                  SizedBox(height: 16.h),
                                  LocaleKeys.visaOrMastercard.tr(context: context).toText16(isBold: true).toShimmer2(isShow: todoVM.isProcessingPayment),
                                ],
                              ),
                              SizedBox(width: 8.h),
                              const Spacer(),
                              Transform.flip(
                                flipX: appState.isArabic(),
                                child: Utils.buildSvgWithAssets(
                                  icon: AppAssets.forward_arrow_icon_small,
                                  iconColor: AppColors.blackColor,
                                  width: 18.h,
                                  height: 13.h,
                                  fit: BoxFit.contain,
                                ).toShimmer2(isShow: todoVM.isProcessingPayment),
                              ),
                            ],
                          ).paddingSymmetrical(16.h, 16.h),
                        ).paddingSymmetrical(24.h, 0.h).onPress(() async {
                          if (!todoVM.isProcessingPayment) {
                            selectedPaymentMethod = "VISA";
                            if (appState.isPaytabsEnabled) {
                              transID = Utils.getAdvancePaymentTransID(
                                widget.projectID,
                                appState.getAuthenticatedUser()!.patientId!,
                              );
                              paytabsViewModel.setPaymentConfiguration(
                                "Ancillary Orders Payment",
                                widget.totalAmount,
                              );
                              paytabsViewModel.startCardPayment(paymentOption: selectedPaymentMethod,
                                  liveServiceID: "0",
                                  isScheduleLiveCare: "false",
                                  appointmentDate: DateUtil.convertDateToString(DateTime.now()),
                                  appointmentNo: "0",
                                  doctorID: "0",
                                  transactionID: transID,
                                  amount: widget.totalAmount.toString(),
                                  fileNumber: appState.getAuthenticatedUser()!.patientId!.toString(),
                                  orderDescription: "Ancillary Orders Payment",
                                  serviceID: ServiceTypeEnum.advancePayment.getIdFromServiceEnum().toString(),
                                  projectID: widget.projectID.toString(),
                                  onSuccess: (PaytabsTransactionResponseModel transactionData) async {
                                final paymentAmount = widget.totalAmount;
                                final fortId = transactionData.transactionReference;
                                final paymentMethod = selectedPaymentMethod;

                                // Call createAdvancePayment with the payment details
                                _createAdvancePayment(
                                  paymentAmount: paymentAmount.toDouble(),
                                  paymentReference: fortId!,
                                  paymentMethod: paymentMethod,
                                );
                              }, onError: (err) {
                                showCommonBottomSheetWithoutHeight(
                                  context,
                                  child: Utils.getErrorWidget(loadingText: err.toString()),
                                  callBackFunc: () {},
                                  isFullScreen: false,
                                  isCloseButtonVisible: true,
                                );
                              });
                            } else {
                              if (appState.isPayfortHostedPageEnabled) {
                                LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingPaymentInformation.tr(context: context));
                                transID = Utils.getAdvancePaymentTransID(
                                  widget.projectID,
                                  appState.getAuthenticatedUser()!.patientId!,
                                );

                                await payfortViewModel.getPayfortConfigurations(
                                  serviceId: ServiceTypeEnum.ancillaryOrder.getIdFromServiceEnum(),
                                  projectId: widget.projectID,
                                  integrationId: 1,
                                );

                                payfortViewModel.initiatePaymentWithCard(
                                  "visa",
                                  "0",
                                  "false",
                                  DateUtil.convertDateToString(DateTime.now()),
                                  "0",
                                  "0",
                                  transactionID: transID,
                                  fileNumber: appState.getAuthenticatedUser()!.patientId.toString(),
                                  amount: widget.totalAmount.toString(),
                                  orderDescription: "Ancillary Order Payment",
                                  onSucceeded: (paymentResult) async {
                                    print("Payment Success Data: ${paymentResult.toString()}");
                                    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingPaymentStatusPleaseWait.tr(context: context));

                                    // Call createAdvancePayment with the payment details
                                    _createAdvancePayment(
                                      paymentAmount: widget.totalAmount,
                                      paymentReference: paymentResult.fortId!,
                                      paymentMethod: selectedPaymentMethod,
                                    );
                                  },
                                  onFailed: (err) {
                                    print("Payment Failed Data: ${err.toString()}");
                                    showCommonBottomSheetWithoutHeight(
                                      context,
                                      child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
                                      callBackFunc: () {},
                                      isFullScreen: false,
                                      isCloseButtonVisible: true,
                                    );
                                  },
                                );
                              } else {
                                _openPaymentURL("visa");
                              }
                            }
                          }
                        }),
                      ],
                    ),
                  ),
                ),
              ),
              // Payment Summary Footer
              todoVM.isProcessingPayment ? SizedBox.shrink() : _buildPaymentSummary()
            ],
          );
        },
      ),
    );
  }

  Widget _buildPaymentSummary() {
    // Calculate amounts
    double amountBeforeTax = 0.0;
    double taxAmount = 0.0;

    for (var proc in widget.selectedProcedures) {
      amountBeforeTax += (proc.patientShare ?? 0);
      taxAmount += (proc.patientTaxAmount ?? 0);
    }

    return Container(
      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
        color: AppColors.whiteColor,
        borderRadius: 24.h,
        hasShadow: false,
      ),
      child: Consumer<PayfortViewModel>(builder: (context, payfortVM, child) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 24.h),
            LocaleKeys.totalAmountToPay.tr(context: context).toText18(isBold: true).paddingSymmetrical(24.h, 0.h),
            SizedBox(height: 17.h),

            // Amount before tax
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                LocaleKeys.amountBeforeTax.tr(context: context).toText14(isBold: true),
                Utils.getPaymentAmountWithSymbol(
                  amountBeforeTax.toStringAsFixed(2).toText16(isBold: true),
                  AppColors.blackColor,
                  13,
                  isSaudiCurrency: true,
                ),
              ],
            ).paddingSymmetrical(24.h, 0.h),

            // VAT 15%
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                LocaleKeys.vat15.tr(context: context).toText14(isBold: true, color: AppColors.greyTextColor),
                Utils.getPaymentAmountWithSymbol(
                  taxAmount.toStringAsFixed(2).toText14(isBold: true, color: AppColors.greyTextColor),
                  AppColors.greyTextColor,
                  13,
                  isSaudiCurrency: true,
                ),
              ],
            ).paddingSymmetrical(24.h, 0.h),

            SizedBox(height: 17.h),

            // Total Amount
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                "".toText14(isBold: true),
                Utils.getPaymentAmountWithSymbol(
                  widget.totalAmount.toStringAsFixed(2).toText24(isBold: true),
                  AppColors.blackColor,
                  17,
                  isSaudiCurrency: true,
                ),
              ],
            ).paddingSymmetrical(24.h, 0.h),

            // Apple Pay Button (iOS only)
            Platform.isIOS && Utils.havePrivilege(103)
                ? Utils.buildSvgWithAssets(
                    icon: AppAssets.apple_pay_button,
                    width: 200.h,
                    height: 80.h,
                    fit: BoxFit.contain,
                    applyThemeColor: false,
                  ).paddingSymmetrical(24.h, 0.h).onPress(() {
                    if (!todoSectionViewModel.isProcessingPayment) {
                      if (Utils.havePrivilege(103)) {
                        _startApplePay();
                      } else {
                        _openPaymentURL("ApplePay");
                      }
                    }
                  })
                : SizedBox(height: 12.h),

            SizedBox(height: 12.h),
          ],
        );
      }),
    );
  }

  void _openPaymentURL(String paymentMethod) {
    todoSectionViewModel.setProcessingPayment(true);

    browser = MyInAppBrowser(
      onExitCallback: _onBrowserExit,
      onLoadStartCallback: _onBrowserLoadStart,
    );

    final user = appState.getAuthenticatedUser();
    transID = Utils.getAdvancePaymentTransID(
      widget.projectID,
      user!.patientId!,
    );

    browser!.openPaymentBrowser(
      widget.totalAmount,
      "Ancillary Order Payment",
      transID,
      widget.projectID.toString(),
      user.emailAddress ?? "CustID_${user.patientId}@HMG.com",
      paymentMethod,
      user.patientType ?? 1,
      "${user.firstName} ${user.lastName}",
      user.patientId,
      user,
      browser!,
      false,
      "3",
      ServiceTypeEnum.ancillaryOrder.getIdFromServiceEnum().toString(),
      context,
      null,
      widget.appointmentNoVida,
      0,
      0,
      null,
    );
  }

  void _onBrowserLoadStart(String url) {
    log("onBrowserLoadStart: $url");

    for (var element in MyInAppBrowser.successURLS) {
      if (url.contains(element)) {
        if (browser!.isOpened()) browser!.close();
        MyInAppBrowser.isPaymentDone = true;
        return;
      }
    }

    for (var element in MyInAppBrowser.errorURLS) {
      if (url.contains(element)) {
        if (browser!.isOpened()) browser!.close();
        MyInAppBrowser.isPaymentDone = false;
        return;
      }
    }
  }

  void _onBrowserExit(bool isPaymentMade) {
    log("onBrowserExit Called: $isPaymentMade");
    _checkPaymentStatus();
  }

  void _checkPaymentStatus() {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.checkingPaymentStatusPleaseWait.tr(context: context));

    todoSectionViewModel.checkPaymentStatus(
      transID: transID,
      onSuccess: (response) {
        String paymentInfo = response['Response_Message'];

        if (paymentInfo == 'Success') {
          // Extract payment details from response
          final paymentAmount = response['Amount'] ?? widget.totalAmount;
          final fortId = response['Fort_id'] ?? transID;
          final paymentMethod = response['PaymentMethod'] ?? selectedPaymentMethod;

          // Call createAdvancePayment with the payment details
          _createAdvancePayment(
            paymentAmount: paymentAmount is String ? double.parse(paymentAmount) : paymentAmount.toDouble(),
            paymentReference: fortId,
            paymentMethod: paymentMethod,
          );
        } else {
          LoaderBottomSheet.hideLoader();
          todoSectionViewModel.setProcessingPayment(false);
          Utils.showToast(response['Response_Message']);
        }
      },
      onError: (error) {
        LoaderBottomSheet.hideLoader();
        todoSectionViewModel.setProcessingPayment(false);
        Utils.showToast(error);
      },
    );
  }

  void _createAdvancePayment({
    required num paymentAmount,
    required String paymentReference,
    required String paymentMethod,
  }) {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.processingPaymentPleaseWait.tr(context: context));

    final user = appState.getAuthenticatedUser();

    todoSectionViewModel.createAdvancePayment(
      projectID: widget.projectID,
      paymentAmount: paymentAmount,
      paymentReference: paymentReference,
      paymentMethodName: paymentMethod,
      patientTypeID: user!.patientType ?? 1,
      patientName: "${user.firstName} ${user.lastName}",
      patientID: user.patientId!,
      // setupID: "010266",
      setupID: widget.setupID,
      isAncillaryOrder: true,
      onSuccess: (response) {
        // Extract advance number from response
        final advanceNumber =
            response['OnlineCheckInAppointments']?[0]?['AdvanceNumber'] ?? response['OnlineCheckInAppointments']?[0]?['AdvanceNumber_VP'] ?? '';

        if (advanceNumber.isNotEmpty) {
          _addAdvancedNumberRequest(
            advanceNumber: advanceNumber.toString(),
            paymentReference: paymentReference,
          );
        } else {
          LoaderBottomSheet.hideLoader();
          todoSectionViewModel.setProcessingPayment(false);
          Utils.showToast("Failed to get advance number");
        }
      },
      onError: (error) {
        LoaderBottomSheet.hideLoader();
        todoSectionViewModel.setProcessingPayment(false);
        Utils.showToast(error);
      },
    );
  }

  void _addAdvancedNumberRequest({
    required String advanceNumber,
    required String paymentReference,
  }) {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.finalizingPaymentPleaseWait.tr(context: context));

    final user = appState.getAuthenticatedUser();

    todoSectionViewModel.addAdvancedNumberRequest(
      advanceNumber: advanceNumber,
      paymentReference: paymentReference,
      appointmentID: 0,
      patientID: user!.patientId!,
      patientTypeID: user.patientType ?? 1,
      patientOutSA: user.outSa ?? 0,
      onSuccess: (response) {
        // After adding advance number, generate invoice
        _autoGenerateInvoice();
      },
      onError: (error) {
        LoaderBottomSheet.hideLoader();
        todoSectionViewModel.setProcessingPayment(false);
        Utils.showToast(error);
      },
    );
  }

  void _autoGenerateInvoice() {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.generatingInvoicePleaseWait.tr(context: context));

    List<dynamic> selectedProcListAPI = widget.selectedProcedures.map((element) {
      return {
        "ApprovalLineItemNo": element.approvalLineItemNo,
        "OrderLineItemNo": element.orderLineItemNo,
        "ProcedureID": element.procedureID,
      };
    }).toList();

    todoSectionViewModel.autoGenerateAncillaryOrdersInvoice(
      orderNo: widget.orderNo,
      projectID: widget.projectID,
      appointmentNo: widget.appointmentNoVida,
      selectedProcedures: selectedProcListAPI,
      languageID: appState.isArabic() ? 1 : 2,
      onSuccess: (response) {
        LoaderBottomSheet.hideLoader();
        final invoiceNo = response['AncillaryOrderInvoiceList']?[0]?['InvoiceNo'];
        _showSuccessDialog(invoiceNo);
      },
      onError: (error) {
        LoaderBottomSheet.hideLoader();
        todoSectionViewModel.setProcessingPayment(false);
        showCommonBottomSheetWithoutHeight(context,
            child: Utils.getErrorWidget(loadingText: error.toString()), isCloseButtonVisible: true, isDismissible: true, isFullScreen: false, callBackFunc: () {});
      },
    );
  }

  void _showSuccessDialog(dynamic invoiceNo) {
    todoSectionViewModel.setProcessingPayment(false);
    // Show success message and navigate
    // Utils.showToast("Payment successful! Invoice #: $invoiceNo");
    // Navigate back to home after a short delay
    // Future.delayed(Duration(seconds: 1), () {
    showCommonBottomSheetWithoutHeight(context,
        child: Utils.getSuccessWidget(loadingText: "${LocaleKeys.paymentCompletedSuccessfully.tr(context: context)}, ${LocaleKeys.hereIsYourInvoiceNumber.tr(context: context)}$invoiceNo"),
        isCloseButtonVisible: true,
        isDismissible: true,
        isFullScreen: false, isAutoDismiss: true, callBackFunc: () {
      // Pop until we reach the LandingPage
      todoSectionViewModel.setIsAncillaryOrdersNeedReloading(true);
      Navigator.pushAndRemoveUntil(
          context,
          CustomPageRoute(
            page: LandingNavigation(),
          ),
          (r) => false);
    });
    // });
  }

  _startApplePay() async {
    LoaderBottomSheet.showLoader(loadingText: LocaleKeys.fetchingApplePayDetails.tr(context: context));
    final user = appState.getAuthenticatedUser();
    transID = Utils.getAdvancePaymentTransID(widget.projectID, user!.patientId!);

    ApplePayInsertRequest applePayInsertRequest = ApplePayInsertRequest();
    await payfortViewModel.getPayfortConfigurations(
      serviceId: ServiceTypeEnum.ancillaryOrder.getIdFromServiceEnum(),
      projectId: widget.projectID,
      integrationId: 2,
    );

    applePayInsertRequest.clientRequestID = transID;
    applePayInsertRequest.clinicID = 0;

    applePayInsertRequest.currency = appState.getAuthenticatedUser()!.outSa! == 0 ? "SAR" : "AED";
    applePayInsertRequest.customerEmail = "CustID_${appState.getAuthenticatedUser()!.patientId.toString()}@HMG.com";
    applePayInsertRequest.customerID = appState.getAuthenticatedUser()!.patientId.toString();
    applePayInsertRequest.customerName = "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}";

    applePayInsertRequest.deviceToken = await Utils.getStringFromPrefs(CacheConst.pushToken);
    applePayInsertRequest.voipToken = await Utils.getStringFromPrefs(CacheConst.voipToken);
    applePayInsertRequest.doctorID = 0;
    applePayInsertRequest.projectID = widget.projectID.toString();
    applePayInsertRequest.serviceID = ServiceTypeEnum.ancillaryOrder.getIdFromServiceEnum().toString();
    applePayInsertRequest.channelID = 3;
    applePayInsertRequest.patientID = appState.getAuthenticatedUser()!.patientId.toString();
    applePayInsertRequest.patientTypeID = appState.getAuthenticatedUser()!.patientType;
    applePayInsertRequest.patientOutSA = appState.getAuthenticatedUser()!.outSa;
    applePayInsertRequest.appointmentDate = DateUtil.convertDateToString(widget.appointmentDate ?? DateTime.now());
    applePayInsertRequest.appointmentNo = widget.appointmentNoVida;
    applePayInsertRequest.orderDescription = "Ancillary Order Payment";
    applePayInsertRequest.liveServiceID = "0";
    applePayInsertRequest.latitude = "0.0";
    applePayInsertRequest.longitude = "0.0";
    applePayInsertRequest.amount = widget.totalAmount.toString();
    applePayInsertRequest.isSchedule = "0";
    applePayInsertRequest.language = appState.isArabic() ? 'ar' : 'en';
    applePayInsertRequest.languageID = appState.isArabic() ? 1 : 2;
    applePayInsertRequest.userName = appState.getAuthenticatedUser()!.patientId;
    applePayInsertRequest.responseContinueURL = "http://hmg.com/Documents/success.html";
    applePayInsertRequest.backClickUrl = "http://hmg.com/Documents/success.html";
    applePayInsertRequest.paymentOption = "ApplePay";

    applePayInsertRequest.isMobSDK = true;
    applePayInsertRequest.merchantReference = transID;
    applePayInsertRequest.merchantIdentifier = payfortViewModel.payfortProjectDetailsRespModel!.merchantIdentifier;
    applePayInsertRequest.commandType = "PURCHASE";
    applePayInsertRequest.signature = payfortViewModel.payfortProjectDetailsRespModel!.signature;
    applePayInsertRequest.accessCode = payfortViewModel.payfortProjectDetailsRespModel!.accessCode;
    applePayInsertRequest.shaRequestPhrase = payfortViewModel.payfortProjectDetailsRespModel!.shaRequest;
    applePayInsertRequest.shaResponsePhrase = payfortViewModel.payfortProjectDetailsRespModel!.shaResponse;
    applePayInsertRequest.returnURL = "";

    try {
      await payfortViewModel.applePayRequestInsert(applePayInsertRequest: applePayInsertRequest);
    } catch (error) {
      log("Apple Pay Insert Request Failed: $error");
      LoaderBottomSheet.hideLoader();
      showCommonBottomSheetWithoutHeight(
        context,
        child: Utils.getErrorWidget(loadingText: LocaleKeys.failedToInitializeApplePay.tr(context: context)),
        callBackFunc: () {},
        isFullScreen: false,
        isCloseButtonVisible: true,
      );
      return;
    }
    // Only proceed with Apple Pay if insert was successful
    if(appState.isPaytabsEnabled) {
      selectedPaymentMethod = "VISA";
      LoaderBottomSheet.hideLoader();
      paytabsViewModel.setPaymentConfiguration(
        "Ancillary Orders Payment",
        widget.totalAmount,
      );
      paytabsViewModel.startApplePayPayment(onSuccess: (PaytabsTransactionResponseModel transactionData) async {
        final paymentAmount = widget.totalAmount;
        final fortId = transactionData.transactionReference;
        final paymentMethod = selectedPaymentMethod;

        // Call createAdvancePayment with the payment details
        _createAdvancePayment(
          paymentAmount: paymentAmount.toDouble(),
          paymentReference: fortId!,
          paymentMethod: paymentMethod,
        );
      }, onError: (err) {
        showCommonBottomSheetWithoutHeight(
          context,
          child: Utils.getErrorWidget(loadingText: err.toString()),
          callBackFunc: () {},
          isFullScreen: false,
          isCloseButtonVisible: true,
        );
      });
    } else {
      payfortViewModel.paymentWithApplePay(
        customerName: "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}",
        customerEmail: "CustID_${appState.getAuthenticatedUser()!.patientId.toString()}@HMG.com",
        orderDescription: "Ancillary Order Payment",
        orderAmount: widget.totalAmount,
        merchantReference: transID,
        merchantIdentifier: payfortViewModel.payfortProjectDetailsRespModel!.merchantIdentifier,
        applePayAccessCode: payfortViewModel.payfortProjectDetailsRespModel!.accessCode,
        applePayShaRequestPhrase: payfortViewModel.payfortProjectDetailsRespModel!.shaRequest,
        currency: appState.getAuthenticatedUser()!.outSa! == 0 ? "SAR" : "AED",
        onFailed: (failureResult) async {
          log("failureResult: ${failureResult.message.toString()}");
          LoaderBottomSheet.hideLoader();
          showCommonBottomSheetWithoutHeight(
            context,
            child: Utils.getErrorWidget(loadingText: failureResult.message.toString()),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
        },
        onSucceeded: (successResult) async {
          LoaderBottomSheet.hideLoader();
          log("successResult: ${successResult.responseMessage.toString()}");
          selectedPaymentMethod = successResult.paymentOption ?? "VISA";
          _checkPaymentStatus();
        },
      );
    }
  }
}
