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

import 'package:amazon_payfort/amazon_payfort.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_amazonpaymentservices/flutter_amazonpaymentservices.dart';
import 'package:hmg_patient_app_new/core/api_consts.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/habib_wallet/habib_wallet_view_model.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/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.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:network_info_plus/network_info_plus.dart';
import 'package:provider/provider.dart';

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

  @override
  State<WalletPaymentConfirmPage> createState() => _WalletPaymentConfirmPageState();
}

class _WalletPaymentConfirmPageState extends State<WalletPaymentConfirmPage> {
  late PayfortViewModel payfortViewModel;
  late PayTabsViewModel paytabsViewModel;
  late AppState appState;
  late HabibWalletViewModel habibWalletVM;

  MyInAppBrowser? browser;
  String selectedPaymentMethod = "";

  String transID = "";

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

  @override
  Widget build(BuildContext context) {
    appState = getIt.get<AppState>();
    habibWalletVM = Provider.of<HabibWalletViewModel>(context, listen: false);
    payfortViewModel = Provider.of<PayfortViewModel>(context, listen: false);
    paytabsViewModel = Provider.of<PayTabsViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.selectPaymentOption.tr(context: context),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 24.h),
                    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: 72.h, height: 25.h, fit: BoxFit.contain).toShimmer2(isShow: false),
                              SizedBox(height: 16.h),
                              LocaleKeys.mada.tr(context: context).toText16(isBold: true).toShimmer2(isShow: false),
                            ],
                          ),
                          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: false),
                          ),
                        ],
                      ).paddingSymmetrical(16.h, 16.h),
                    ).paddingSymmetrical(24.h, 0.h).onPress(() async {
                      selectedPaymentMethod = "MADA";
                      if (appState.isPaytabsEnabled) {
                        transID = Utils.getAdvancePaymentTransID(habibWalletVM.selectedHospital!.iD!, int.parse(habibWalletVM.fileNumber));
                        paytabsViewModel.setPaymentConfiguration("Advance Payment", habibWalletVM.walletRechargeAmount);
                        paytabsViewModel.startCardPayment(
                            paymentOption: selectedPaymentMethod,
                            liveServiceID: "0",
                            isScheduleLiveCare: "false",
                            appointmentDate: DateUtil.convertDateToString(DateTime.now()),
                            appointmentNo: "0",
                            doctorID: "0",
                            transactionID: transID,
                            amount: habibWalletVM.walletRechargeAmount.toString(),
                            fileNumber: habibWalletVM.fileNumber.toString(),
                            orderDescription: "Advance Payment",
                            serviceID: ServiceTypeEnum.advancePayment.getIdFromServiceEnum().toString(),
                            projectID: habibWalletVM.selectedHospital!.iD!.toString(),
                            onSuccess: (PaytabsTransactionResponseModel transactionData) async {
                              LoaderBottomSheet.showLoader();
                          await habibWalletVM.HISCreateAdvancePayment(
                              paymentMethodName: selectedPaymentMethod,
                              paidAmount: habibWalletVM.walletRechargeAmount,
                              paymentReference: transactionData.transactionReference!,
                              patientID: habibWalletVM.fileNumber,
                              projectID: habibWalletVM.selectedHospital!.iD!,
                              depositorName: habibWalletVM.depositorName,
                              onSuccess: (value) async {
                                await habibWalletVM.addAdvanceNumberRequest(
                                    advanceNumber: Utils.isVidaPlusProject(habibWalletVM.selectedHospital!.iD)
                                        ? value.data['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString()
                                        : value.data['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
                                    paymentReference: transactionData.transactionReference!,
                                    onSuccess: (value) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(getIt.get<NavigationService>().navigatorKey.currentContext!, child: Utils.getSuccessWidget(loadingText: "Payment Successful!"),
                                          callBackFunc: () {
                                        habibWalletVM.setIsWalletAmountToBeLoaded(true);
                                        habibWalletVM.initHabibWalletProvider();
                                        habibWalletVM.getPatientBalanceAmount();
                                        Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                                        Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                                      }, isFullScreen: false, isCloseButtonVisible: true, isAutoDismiss: true);
                                    },
                                    onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(
                                        context,
                                        child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
                                        callBackFunc: () {},
                                        isFullScreen: false,
                                        isCloseButtonVisible: true,
                                      );
                                    });
                              },
                              onError: (err) {
                                LoaderBottomSheet.hideLoader();
                                showCommonBottomSheetWithoutHeight(
                                  context,
                                  child: Utils.getErrorWidget(loadingText: err),
                                  callBackFunc: () {},
                                  isFullScreen: false,
                                  isCloseButtonVisible: true,
                                );
                              });
                        }, onError: (err) {
                          LoaderBottomSheet.showLoader();
                          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(habibWalletVM.selectedHospital!.iD!, int.parse(habibWalletVM.fileNumber));
                          await payfortViewModel.getPayfortConfigurations(
                              serviceId: ServiceTypeEnum.advancePayment.getIdFromServiceEnum(), projectId: habibWalletVM.selectedHospital!.iD!, integrationId: 1);

                          payfortViewModel.initiatePaymentWithCard(
                            "mada",
                            "0",
                            "false",
                            DateUtil.convertDateToString(DateTime.now()),
                            "0",
                            "0",
                            transactionID: transID,
                            fileNumber: habibWalletVM.fileNumber.toString(),
                            amount: habibWalletVM.walletRechargeAmount.toString(),
                            orderDescription: "Advance Payment",
                            onSucceeded: (paymentResult) async {
                              print("Payment Success Data: ${paymentResult.toString()}");
                              LoaderBottomSheet.showLoader();
                              await habibWalletVM.HISCreateAdvancePayment(
                                  paymentMethodName: selectedPaymentMethod,
                                  paidAmount: habibWalletVM.walletRechargeAmount,
                                  paymentReference: paymentResult.fortId!,
                                  patientID: habibWalletVM.fileNumber,
                                  projectID: habibWalletVM.selectedHospital!.iD!,
                                  depositorName: habibWalletVM.depositorName,
                                  onSuccess: (value) async {
                                    await habibWalletVM.addAdvanceNumberRequest(
                                        advanceNumber: Utils.isVidaPlusProject(habibWalletVM.selectedHospital!.iD)
                                            ? value.data['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString()
                                            : value.data['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
                                        paymentReference: paymentResult.fortId!,
                                        onSuccess: (value) {
                                          LoaderBottomSheet.hideLoader();
                                          showCommonBottomSheetWithoutHeight(getIt.get<NavigationService>().navigatorKey.currentContext!,
                                              child: Utils.getSuccessWidget(loadingText: "Payment Successful!"), callBackFunc: () {
                                            habibWalletVM.setIsWalletAmountToBeLoaded(true);
                                            habibWalletVM.initHabibWalletProvider();
                                            habibWalletVM.getPatientBalanceAmount();
                                            // Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                                            Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                                          }, isFullScreen: false, isCloseButtonVisible: true, isAutoDismiss: true);
                                        },
                                        onError: (err) {
                                          LoaderBottomSheet.hideLoader();
                                          showCommonBottomSheetWithoutHeight(
                                            context,
                                            child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
                                            callBackFunc: () {},
                                            isFullScreen: false,
                                            isCloseButtonVisible: true,
                                          );
                                        });
                                  },
                                  onError: (err) {
                                    LoaderBottomSheet.hideLoader();
                                    showCommonBottomSheetWithoutHeight(
                                      context,
                                      child: Utils.getErrorWidget(loadingText: err),
                                      callBackFunc: () {},
                                      isFullScreen: false,
                                      isCloseButtonVisible: true,
                                    );
                                  });
                            },
                            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),
                    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: 40.h, height: 40.h),
                                  SizedBox(width: 8.h),
                                  Utils.buildImgWithAssets(icon: AppAssets.mastercard, width: 40.h, height: 40.h, fit: BoxFit.contain),
                                ],
                              ).toShimmer2(isShow: false),
                              SizedBox(height: 16.h),
                              LocaleKeys.visaOrMastercard.tr(context: context).toText16(isBold: true).toShimmer2(isShow: false),
                            ],
                          ),
                          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: false),
                          ),
                        ],
                      ).paddingSymmetrical(16.h, 16.h),
                    ).paddingSymmetrical(24.h, 0.h).onPress(() async {
                      selectedPaymentMethod = "VISA";
                      if (appState.isPaytabsEnabled) {
                        transID = Utils.getAdvancePaymentTransID(habibWalletVM.selectedHospital!.iD!, int.parse(habibWalletVM.fileNumber));
                        paytabsViewModel.setPaymentConfiguration("Advance Payment", habibWalletVM.walletRechargeAmount);
                        paytabsViewModel.startCardPayment(
                            paymentOption: selectedPaymentMethod,
                            liveServiceID: "0",
                            isScheduleLiveCare: "false",
                            appointmentDate: DateUtil.convertDateToString(DateTime.now()),
                            appointmentNo: "0",
                            doctorID: "0",
                            transactionID: transID,
                            amount: habibWalletVM.walletRechargeAmount.toString(),
                            fileNumber: habibWalletVM.fileNumber.toString(),
                            orderDescription: "Advance Payment",
                            serviceID: ServiceTypeEnum.advancePayment.getIdFromServiceEnum().toString(),
                            projectID: habibWalletVM.selectedHospital!.iD!.toString(),
                            onSuccess: (PaytabsTransactionResponseModel transactionData) async {
                              LoaderBottomSheet.showLoader();
                          await habibWalletVM.HISCreateAdvancePayment(
                              paymentMethodName: selectedPaymentMethod,
                              paidAmount: habibWalletVM.walletRechargeAmount,
                              paymentReference: transactionData.transactionReference!,
                              patientID: habibWalletVM.fileNumber,
                              projectID: habibWalletVM.selectedHospital!.iD!,
                              depositorName: habibWalletVM.depositorName,
                              onSuccess: (value) async {
                                await habibWalletVM.addAdvanceNumberRequest(
                                    advanceNumber: Utils.isVidaPlusProject(habibWalletVM.selectedHospital!.iD)
                                        ? value.data['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString()
                                        : value.data['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
                                    paymentReference: transactionData.transactionReference!,
                                    onSuccess: (value) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(getIt.get<NavigationService>().navigatorKey.currentContext!, child: Utils.getSuccessWidget(loadingText: "Payment Successful!"),
                                          callBackFunc: () {
                                        habibWalletVM.setIsWalletAmountToBeLoaded(true);
                                        habibWalletVM.initHabibWalletProvider();
                                        habibWalletVM.getPatientBalanceAmount();
                                        Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                                        Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                                      }, isFullScreen: false, isCloseButtonVisible: true, isAutoDismiss: true);
                                    },
                                    onError: (err) {
                                      LoaderBottomSheet.hideLoader();
                                      showCommonBottomSheetWithoutHeight(
                                        context,
                                        child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
                                        callBackFunc: () {},
                                        isFullScreen: false,
                                        isCloseButtonVisible: true,
                                      );
                                    });
                              },
                              onError: (err) {
                                LoaderBottomSheet.hideLoader();
                                showCommonBottomSheetWithoutHeight(
                                  context,
                                  child: Utils.getErrorWidget(loadingText: err),
                                  callBackFunc: () {},
                                  isFullScreen: false,
                                  isCloseButtonVisible: true,
                                );
                              });
                        }, 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(habibWalletVM.selectedHospital!.iD!, int.parse(habibWalletVM.fileNumber));
                          await payfortViewModel.getPayfortConfigurations(
                              serviceId: ServiceTypeEnum.advancePayment.getIdFromServiceEnum(), projectId: habibWalletVM.selectedHospital!.iD!, integrationId: 1);

                          payfortViewModel.initiatePaymentWithCard(
                            "visa",
                            "0",
                            "false",
                            DateUtil.convertDateToString(DateTime.now()),
                            "0",
                            "0",
                            transactionID: transID,
                            fileNumber: habibWalletVM.fileNumber.toString(),
                            amount: habibWalletVM.walletRechargeAmount.toString(),
                            orderDescription: "Advance Payment",
                            onSucceeded: (paymentResult) async {
                              print("Payment Success Data: ${paymentResult.toString()}");
                              LoaderBottomSheet.showLoader();
                              await habibWalletVM.HISCreateAdvancePayment(
                                  paymentMethodName: selectedPaymentMethod,
                                  paidAmount: habibWalletVM.walletRechargeAmount,
                                  paymentReference: paymentResult.fortId!,
                                  patientID: habibWalletVM.fileNumber,
                                  projectID: habibWalletVM.selectedHospital!.iD!,
                                  depositorName: habibWalletVM.depositorName,
                                  onSuccess: (value) async {
                                    await habibWalletVM.addAdvanceNumberRequest(
                                        advanceNumber: Utils.isVidaPlusProject(habibWalletVM.selectedHospital!.iD)
                                            ? value.data['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString()
                                            : value.data['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
                                        paymentReference: paymentResult.fortId!,
                                        onSuccess: (value) {
                                          LoaderBottomSheet.hideLoader();
                                          showCommonBottomSheetWithoutHeight(getIt.get<NavigationService>().navigatorKey.currentContext!,
                                              child: Utils.getSuccessWidget(loadingText: "Payment Successful!"), callBackFunc: () {
                                            habibWalletVM.setIsWalletAmountToBeLoaded(true);
                                            habibWalletVM.initHabibWalletProvider();
                                            habibWalletVM.getPatientBalanceAmount();
                                            Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                                            // Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                                          }, isFullScreen: false, isCloseButtonVisible: true, isAutoDismiss: true);
                                        },
                                        onError: (err) {
                                          LoaderBottomSheet.hideLoader();
                                          showCommonBottomSheetWithoutHeight(
                                            context,
                                            child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
                                            callBackFunc: () {},
                                            isFullScreen: false,
                                            isCloseButtonVisible: true,
                                          );
                                        });
                                  },
                                  onError: (err) {
                                    LoaderBottomSheet.hideLoader();
                                    showCommonBottomSheetWithoutHeight(
                                      context,
                                      child: Utils.getErrorWidget(loadingText: err),
                                      callBackFunc: () {},
                                      isFullScreen: false,
                                      isCloseButtonVisible: true,
                                    );
                                  });
                            },
                            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");
                        }
                      }
                    }),
                  ],
                ),
              ),
            ),
          ),
          Container(
            // height: 200.h,
            width: MediaQuery.of(context).size.width,
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: true,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 24.h),
                habibWalletVM.depositorName.toText18(isBold: true).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 12.h),
                Wrap(
                  direction: Axis.horizontal,
                  spacing: 4.h,
                  runSpacing: 4.h,
                  children: [
                    AppCustomChipWidget(
                      labelText: "${LocaleKeys.fileno.tr(context: context)}.: ${habibWalletVM.fileNumber}",
                      isEnglishOnly: true,
                    ),
                    AppCustomChipWidget(
                      labelText: "${LocaleKeys.mobileNumber.tr(context: context)}: ${habibWalletVM.mobileNumber}",
                      isEnglishOnly: true,
                    ),
                    AppCustomChipWidget(
                      labelText: "${habibWalletVM.selectedHospital!.name}",
                    ),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 16.h),
                Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.1), height: 1.h).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 16.h),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    LocaleKeys.totalAmountToPay.tr(context: context).toText16(isBold: true),
                    Utils.getPaymentAmountWithSymbol(
                        NumberFormat.decimalPattern().format(habibWalletVM.walletRechargeAmount).toString().toText24(isBold: true, isEnglishOnly: true), AppColors.blackColor, 15.h,
                        isSaudiCurrency: true),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 12.h),
                Platform.isIOS
                    ? Utils.buildSvgWithAssets(icon: AppAssets.apple_pay_button, width: 200.h, height: 56.h, fit: BoxFit.contain, applyThemeColor: false).paddingSymmetrical(24.h, 0.h).onPress(() {
                        if (Utils.havePrivilege(103)) {
                          startApplePay();
                        } else {
                          openPaymentURL("ApplePay");
                        }
                      })
                    : SizedBox(height: 12.h),
                SizedBox(height: 32.h),
              ],
            ),
          ),
        ],
      ),
    );
  }

  startApplePay() async {
    LoaderBottomSheet.showLoader();
    ApplePayInsertRequest applePayInsertRequest = ApplePayInsertRequest();

    transID = Utils.getAdvancePaymentTransID(habibWalletVM.selectedHospital!.iD!, int.parse(habibWalletVM.fileNumber));

    await payfortViewModel.getPayfortConfigurations(serviceId: ServiceTypeEnum.advancePayment.getIdFromServiceEnum(), projectId: habibWalletVM.selectedHospital!.iD!, integrationId: 2);

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

    applePayInsertRequest.currency = appState.getAuthenticatedUser()!.outSa! == 0 ? "SAR" : "AED";
    applePayInsertRequest.customerEmail = "CustID_${habibWalletVM.fileNumber.toString()}@HMG.com";
    applePayInsertRequest.customerID = habibWalletVM.fileNumber.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 = habibWalletVM.selectedHospital!.iD!.toString();
    applePayInsertRequest.serviceID = ServiceTypeEnum.appointmentPayment.getIdFromServiceEnum().toString();
    applePayInsertRequest.channelID = 3;
    applePayInsertRequest.patientID = habibWalletVM.fileNumber.toString();
    applePayInsertRequest.patientTypeID = appState.getAuthenticatedUser()!.patientType;
    applePayInsertRequest.patientOutSA = appState.getAuthenticatedUser()!.outSa;
    applePayInsertRequest.appointmentDate = null;
    applePayInsertRequest.appointmentNo = 0;
    applePayInsertRequest.orderDescription = "Advance Payment";
    applePayInsertRequest.liveServiceID = "0";
    applePayInsertRequest.latitude = "0.0";
    applePayInsertRequest.longitude = "0.0";
    applePayInsertRequest.amount = habibWalletVM.walletRechargeAmount.toString();
    applePayInsertRequest.isSchedule = "0";
    applePayInsertRequest.language = appState.isArabic() ? 'ar' : 'en';
    applePayInsertRequest.languageID = appState.isArabic() ? 1 : 2;
    applePayInsertRequest.userName = int.parse(habibWalletVM.fileNumber);
    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 = "";

    //TODO: Need to pass dynamic params to the Apple Pay instead of static values
    await payfortViewModel.applePayRequestInsert(applePayInsertRequest: applePayInsertRequest).then((value) {
      if(appState.isPaytabsEnabled) {
        selectedPaymentMethod = "VISA";
        LoaderBottomSheet.hideLoader();
        paytabsViewModel.setPaymentConfiguration("Advance Payment", habibWalletVM.walletRechargeAmount);
        paytabsViewModel.startApplePayPayment(onSuccess: (PaytabsTransactionResponseModel transactionData) async {
          LoaderBottomSheet.showLoader();
          await habibWalletVM.HISCreateAdvancePayment(
              paymentMethodName: selectedPaymentMethod,
              paidAmount: habibWalletVM.walletRechargeAmount,
              paymentReference: transactionData.transactionReference!,
              patientID: habibWalletVM.fileNumber,
              projectID: habibWalletVM.selectedHospital!.iD!,
              depositorName: habibWalletVM.depositorName,
              onSuccess: (value) async {
                await habibWalletVM.addAdvanceNumberRequest(
                    advanceNumber: Utils.isVidaPlusProject(habibWalletVM.selectedHospital!.iD)
                        ? value.data['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString()
                        : value.data['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
                    paymentReference: transactionData.transactionReference!,
                    onSuccess: (value) {
                      LoaderBottomSheet.hideLoader();
                      showCommonBottomSheetWithoutHeight(getIt.get<NavigationService>().navigatorKey.currentContext!, child: Utils.getSuccessWidget(loadingText: "Payment Successful!"),
                          callBackFunc: () {
                        habibWalletVM.setIsWalletAmountToBeLoaded(true);
                        habibWalletVM.initHabibWalletProvider();
                        habibWalletVM.getPatientBalanceAmount();
                            Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                            Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                          }, isFullScreen: false, isCloseButtonVisible: true, isAutoDismiss: true);
                    },
                    onError: (err) {
                      LoaderBottomSheet.hideLoader();
                      showCommonBottomSheetWithoutHeight(
                        context,
                        child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
                        callBackFunc: () {},
                        isFullScreen: false,
                        isCloseButtonVisible: true,
                      );
                    });
              },
              onError: (err) {
                LoaderBottomSheet.hideLoader();
                showCommonBottomSheetWithoutHeight(
                  context,
                  child: Utils.getErrorWidget(loadingText: err),
                  callBackFunc: () {},
                  isFullScreen: false,
                  isCloseButtonVisible: true,
                );
              });
        }, 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: projectViewModel.authenticatedUserObject.user.emailAddress,
          customerEmail: "CustID_${appState.getAuthenticatedUser()!.patientId.toString()}@HMG.com",
          orderDescription: "Advance Payment",
          orderAmount: double.parse(habibWalletVM.walletRechargeAmount.toString()),
          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()}");
            showCommonBottomSheetWithoutHeight(
              context,
              child: Utils.getErrorWidget(loadingText: failureResult.message.toString()),
              callBackFunc: () {},
              isFullScreen: false,
              isCloseButtonVisible: true,
            );
          },
          onSucceeded: (successResult) async {
            log("successResult: ${successResult.responseMessage.toString()}");
            selectedPaymentMethod = successResult.paymentOption ?? "VISA";
            checkPaymentStatus();
          },
        );
      }
    });
  }

  void checkPaymentStatus() async {
    LoaderBottomSheet.showLoader();
    await payfortViewModel.checkPaymentStatus(
      transactionID: transID,
      onSuccess: (apiResponse) async {
        print(apiResponse.data);
        if (payfortViewModel.payfortCheckPaymentStatusResponseModel!.responseMessage!.toLowerCase() == "success") {
          await habibWalletVM.HISCreateAdvancePayment(
              paymentMethodName: selectedPaymentMethod,
              paidAmount: habibWalletVM.walletRechargeAmount,
              paymentReference: payfortViewModel.payfortCheckPaymentStatusResponseModel!.fortId!,
              patientID: habibWalletVM.fileNumber,
              projectID: habibWalletVM.selectedHospital!.iD!,
              depositorName: habibWalletVM.depositorName,
              onSuccess: (value) async {
                await habibWalletVM.addAdvanceNumberRequest(
                    advanceNumber: Utils.isVidaPlusProject(habibWalletVM.selectedHospital!.iD)
                        ? value.data['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString()
                        : value.data['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
                    paymentReference: payfortViewModel.payfortCheckPaymentStatusResponseModel!.fortId!,
                    onSuccess: (value) {
                      LoaderBottomSheet.hideLoader();
                      showCommonBottomSheetWithoutHeight(getIt.get<NavigationService>().navigatorKey.currentContext!, child: Utils.getSuccessWidget(loadingText: "Payment Successful!"),
                          callBackFunc: () {
                        habibWalletVM.setIsWalletAmountToBeLoaded(true);
                        habibWalletVM.initHabibWalletProvider();
                        habibWalletVM.getPatientBalanceAmount();
                        Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                        Navigator.of(getIt.get<NavigationService>().navigatorKey.currentContext!).pop();
                      }, isFullScreen: false, isCloseButtonVisible: true, isAutoDismiss: true);
                    },
                    onError: (err) {
                      LoaderBottomSheet.hideLoader();
                      showCommonBottomSheetWithoutHeight(
                        context,
                        child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
                        callBackFunc: () {},
                        isFullScreen: false,
                        isCloseButtonVisible: true,
                      );
                    });
              },
              onError: (err) {
                LoaderBottomSheet.hideLoader();
                showCommonBottomSheetWithoutHeight(
                  context,
                  child: Utils.getErrorWidget(loadingText: err),
                  callBackFunc: () {},
                  isFullScreen: false,
                  isCloseButtonVisible: true,
                );
              });
        } else {
          LoaderBottomSheet.hideLoader();
          showCommonBottomSheetWithoutHeight(
            context,
            child: Utils.getErrorWidget(loadingText: LocaleKeys.paymentFailedPleaseTryAgain.tr(context: context)),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
        }
      },
    );
  }

  onBrowserLoadStart(String url) {
    print("onBrowserLoadStart");
    print(url);

    if (selectedPaymentMethod == "tamara") {
      if (Platform.isAndroid) {
        Uri uri = new Uri.dataFromString(url);
        // tamaraPaymentStatus = uri.queryParameters['status']!;
        // tamaraOrderID = uri.queryParameters['AuthorizePaymentId']!;
      } else {
        Uri uri = new Uri.dataFromString(url);
        // tamaraPaymentStatus = uri.queryParameters['paymentStatus']!;
        // tamaraOrderID = uri.queryParameters['orderId']!;
      }
    }

    // if(selectedPaymentMethod != "TAMARA") {
    MyInAppBrowser.successURLS.forEach((element) {
      if (url.contains(element)) {
        browser?.close();
        MyInAppBrowser.isPaymentDone = true;
        return;
      }
    });
    // }

    // if(selectedPaymentMethod != "TAMARA") {
    MyInAppBrowser.errorURLS.forEach((element) {
      if (url.contains(element)) {
        browser?.close();
        MyInAppBrowser.isPaymentDone = false;
        return;
      }
    });
    // }
  }

  onBrowserExit(bool isPaymentMade) async {
    print("onBrowserExit Called!!!!");
    if (selectedPaymentMethod == "TAMARA") {
      // checkTamaraPaymentStatus(transID!, appo);
      // if (tamaraPaymentStatus != null && tamaraPaymentStatus.toLowerCase() == "approved") {
      //   updateTamaraRequestStatus("success", "14", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID, num.parse(selectedInstallments), appo);
      // } else {
      //   updateTamaraRequestStatus("Failed", "00", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID, num.parse(selectedInstallments), appo);
      // }
    } else {
      checkPaymentStatus();
      // checkPaymentStatus(appo);
    }
  }

  openPaymentURL(String paymentMethod) {
    browser = MyInAppBrowser(onExitCallback: onBrowserExit, onLoadStartCallback: onBrowserLoadStart, context: context);
    transID = Utils.getAdvancePaymentTransID(habibWalletVM.selectedHospital!.iD!, int.parse(habibWalletVM.fileNumber));

    browser?.openPaymentBrowser(
        habibWalletVM.walletRechargeAmount,
        "Advance Payment",
        transID,
        habibWalletVM.selectedHospital!.iD!.toString(),
        "CustID_${habibWalletVM.fileNumber.toString()}@HMG.com",
        selectedPaymentMethod,
        appState.getAuthenticatedUser()!.patientType.toString(),
        habibWalletVM.depositorName,
        habibWalletVM.fileNumber.toString(),
        appState.getAuthenticatedUser()!,
        browser!,
        false,
        "3",
        "0",
        context,
        "",
        "",
        "",
        "",
        "3");
  }

  Future<void> runSafePayment(Map<String, dynamic> requestParam, {String sdkToken = ""}) async {
    dynamic result;

    try {
      // Force a 100ms microtask buffer to isolate the UI rendering channel
      await Future.delayed(const Duration(milliseconds: 350));

      result = await FlutterAmazonpaymentservices.normalPay(requestParam, ApiConsts.payFortEnvironmentType, isShowResponsePage: true);

      print("Payment Success Data: ${result.toString()}");
    } on PlatformException catch (e) {
      // If the error is the MethodChannel duplicate reply bug, handle it safely
      if (e.message != null && e.message!.contains("Reply already submitted")) {
        print("Swallowed native channel race-condition crash safely.");
        return;
      }

      // Process real payment rejection errors here
      print("Actual Payment Failure: ${e.details.toString()}");
    } catch (error) {
      print("Generic Error: $error");
    }
  }
}
