import 'dart:developer';
import 'dart:ui';

import 'package:auto_size_text/auto_size_text.dart' show AutoSizeText;
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/enum/PayfortEnums.dart';
import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:hmg_patient_app/models/Authentication/authenticated_user.dart';
import 'package:hmg_patient_app/models/LiveCare/ApplePayInsertRequest.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/services/livecare_services/livecare_provider.dart';
import 'package:hmg_patient_app/services/payfort_services/payfort_project_details_resp_model.dart';
import 'package:hmg_patient_app/services/payfort_services/payfort_view_model.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/buttons/custom_text_button.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/dialogs/alert_dialog.dart';
import 'package:hmg_patient_app/widgets/dialogs/location_selection_dialog.dart' show LocationSelectionDialog;
import 'package:hmg_patient_app/widgets/in_app_browser/InAppBrowser.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:provider/provider.dart';

import '../../../widgets/dialogs/confirm_dialog.dart';
import '../../ToDoList/payment_method_select.dart';

class OfferDetailsPage extends StatefulWidget {
  final String title;
  VoidCallback? onLoginClick;

  OfferDetailsPage({super.key, required this.title, required this.onLoginClick});

  @override
  State<OfferDetailsPage> createState() => _OfferDetailsPageState();
}

class _OfferDetailsPageState extends State<OfferDetailsPage> {
  HospitalsModel? selectedHospital;

  late ProjectViewModel projectViewModel;

  String selectedPaymentMethod = "VISA";
  String transID = "";

  late String tamaraPaymentStatus;
  late String tamaraOrderID;
  late MyInAppBrowser browser;

  num paymentAmount = 295.0;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      isShowDecPage: false,
      isShowAppBar: false,
      showNewAppBar: true,
      isHelp: true,
      showNewAppBarTitle: true,
      appBarTitle: widget.title,
      body: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  /// Banner
                  SvgPicture.asset(
                    "assets/images/svg/details_page_banner.svg",
                    height: 120,
                    fit: BoxFit.fill,
                  ),

                  /// Arabic Offer Section
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 32.0),
                    child: Column(
                      children: [
                        // Padding(
                        //   padding: const EdgeInsets.only(top: 32),
                        //   child: Directionality(
                        //     textDirection: TextDirection.rtl,
                        //     child: Column(
                        //       crossAxisAlignment: CrossAxisAlignment.start,
                        //       children: [
                        //         Text(
                        //           projectViewModel.hisProjectOffers.first.titleArabic!,
                        //           style: TextStyle(
                        //             fontFamily: 'Cairo',
                        //             fontSize: 22,
                        //             fontWeight: FontWeight.bold,
                        //             color: Color(0xff008b4c),
                        //           ),
                        //         ),
                        //         Text(
                        //           projectViewModel.hisProjectOffers.first.descriptionArabic!,
                        //           style: TextStyle(
                        //             fontFamily: 'Cairo',
                        //             fontWeight: FontWeight.w300,
                        //             fontSize: 16,
                        //           ),
                        //         ),
                        //         SizedBox(height: 12),
                        //         Text(
                        //           projectViewModel.hisProjectOffers.first.detailsArabic!,
                        //           style: TextStyle(
                        //             fontFamily: 'Cairo',
                        //             fontWeight: FontWeight.w300,
                        //             fontSize: 14,
                        //           ),
                        //         ),
                        //       ],
                        //     ),
                        //   ),
                        // ),

                        // const SizedBox(height: 20),
                        // const Divider(thickness: 1, color: Color(0xff008b4c)),
                        const SizedBox(height: 20),

                        /// English Offer Section
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                projectViewModel.isArabic
                                    ? projectViewModel.hisProjectOffers.first.titleArabic!.split("\$")[0].trim()
                                    : projectViewModel.hisProjectOffers.first.titleName!.split("\$")[0].trim(),
                                style: TextStyle(
                                  fontSize: 22,
                                  fontWeight: FontWeight.bold,
                                  color: Color(0xff008b4c),
                                ),
                              ),
                              Text(
                                projectViewModel.isArabic ? projectViewModel.hisProjectOffers.first.descriptionArabic! : projectViewModel.hisProjectOffers.first.descriptionEnglish!,
                                style: TextStyle(
                                  // fontFamily: 'Poppins',
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              SizedBox(height: 12),
                              Text(
                                projectViewModel.isArabic ? projectViewModel.hisProjectOffers.first.detailsArabic! : projectViewModel.hisProjectOffers.first.detailsEnglish!,
                                style: TextStyle(
                                  fontSize: 14,
                                  // fontFamily: 'Poppins',
                                ),
                              ),
                            ],
                          ),
                        ),

                        const SizedBox(height: 24),

                        /// Hospital Dropdown (mock UI)
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16),
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                            decoration: BoxDecoration(
                              color: Colors.grey.shade300,
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: InkWell(
                              onTap: () {
                                openHospitalSelection(context);
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Expanded(
                                    child: Column(
                                      children: [
                                        Directionality(
                                          textDirection: TextDirection.rtl,
                                          child: Text(
                                            selectedHospital?.nameN ?? TranslationBase.of(context).selectHospital,
                                            style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontFamily: 'Cairo',
                                            ),
                                          ),
                                        ),
                                        Text(
                                          selectedHospital?.name ?? TranslationBase.of(context).selectHospital,
                                          style: TextStyle(
                                            fontWeight: FontWeight.bold,
                                            fontFamily: 'Poppins',
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Icon(Icons.arrow_drop_down),
                                ],
                              ),
                            ),
                          ),
                        ),

                        const SizedBox(height: 24),

                        /// Buttons
                      ],
                    ),
                  ),

                  const SizedBox(height: 30),
                ],
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 12.0, right: 12.0, bottom: 8),
            child: Row(
              children: [
                SizedBox(
                  width: MediaQuery.of(context).size.width - 24,
                  height: 50,
                  child: DefaultButton("Pay Now      ادفع الآن", () {
                    if (projectViewModel.isLogin) {
                      if (selectedHospital != null) {
                        startPaymentProcess(context);
                      } else {
                        AppToast.showErrorToast(message: TranslationBase.of(context).selectHospital);
                      }
                    } else {
                      ConfirmDialog dialog = new ConfirmDialog(
                          context: context,
                          confirmMessage: TranslationBase.of(context).loginToUseService,
                          okText: TranslationBase.of(context).confirm,
                          cancelText: TranslationBase.of(context).cancel_nocaps,
                          okFunction: () {
                            Navigator.of(context).pop();
                            widget.onLoginClick!();
                          },
                          cancelFunction: () => {});
                      dialog.showAlertDialog(context);
                    }
                  }),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  startPaymentProcess(BuildContext context) {
    Navigator.push(
      context,
      FadePage(
        page: PaymentMethod(
            onSelectedMethod: (String metohd, [String? selectedInstallmentPlan]) {
              selectedPaymentMethod = metohd;
            },
            patientShare: paymentAmount,
            isShowInstallments: false,
            isFromAdvancePayment: true),
      ),
    ).then((value) {
      if (selectedPaymentMethod == "ApplePay") {
        if (projectViewModel.havePrivilege(103)) {
          startApplePay(context);
        } else {
          openPayment(selectedPaymentMethod, projectViewModel.authenticatedUserObject.user, paymentAmount, AppoitmentAllHistoryResultList());
        }
      } else {
        openPayment(selectedPaymentMethod, projectViewModel.authenticatedUserObject.user, paymentAmount, AppoitmentAllHistoryResultList());
      }
    });
  }

  void startApplePay(BuildContext context) async {
    transID = Utils.getAdvancePaymentTransID(selectedHospital!.iD!, projectViewModel.authenticatedUserObject.user.patientID!);
    print("TransactionID: $transID");
    GifLoaderDialogUtils.showMyDialog(context);

    LiveCareService service = new LiveCareService();
    ApplePayInsertRequest applePayInsertRequest = new ApplePayInsertRequest();

    PayfortProjectDetailsRespModel? payfortProjectDetailsRespModel;
    await context.read<PayfortViewModel>().getProjectDetailsForPayfort(projectId: selectedHospital!.iD!, serviceId: projectViewModel.hisProjectOffers.first.serviceId).then((value) {
      payfortProjectDetailsRespModel = value!;
    });

    applePayInsertRequest.clientRequestID = transID;
    applePayInsertRequest.clinicID = 0;
    applePayInsertRequest.currency = projectViewModel.authenticatedUserObject.user.outSA == 1 ? "AED" : "SAR";
    // applePayInsertRequest.customerEmail = projectViewModel.authenticatedUserObject.user.emailAddress;
    applePayInsertRequest.customerEmail = "CustID_${projectViewModel.authenticatedUserObject.user.patientID}@HMG.com";
    applePayInsertRequest.customerID = projectViewModel.authenticatedUserObject.user.patientID;
    applePayInsertRequest.customerName = projectViewModel.authenticatedUserObject.user.firstName! + " " + projectViewModel.authenticatedUserObject.user.lastName!;
    applePayInsertRequest.deviceToken = await AppSharedPreferences().getString(PUSH_TOKEN);
    applePayInsertRequest.voipToken = await AppSharedPreferences().getString(ONESIGNAL_APNS_TOKEN);
    applePayInsertRequest.doctorID = 0;
    applePayInsertRequest.projectID = selectedHospital!.iD.toString();
    applePayInsertRequest.serviceID = projectViewModel.hisProjectOffers.first.serviceId.toString();
    applePayInsertRequest.channelID = 3;
    applePayInsertRequest.patientID = projectViewModel.authenticatedUserObject.user.patientID;
    applePayInsertRequest.patientTypeID = projectViewModel.authenticatedUserObject.user.patientType;
    applePayInsertRequest.patientOutSA = projectViewModel.authenticatedUserObject.user.outSA;
    applePayInsertRequest.appointmentDate = null;
    applePayInsertRequest.appointmentNo = 0;
    applePayInsertRequest.orderDescription = "Advance Payment";
    applePayInsertRequest.liveServiceID = "0";
    applePayInsertRequest.latitude = "0.0";
    applePayInsertRequest.longitude = "0.0";
    applePayInsertRequest.amount = paymentAmount.toString();
    applePayInsertRequest.isSchedule = "0";
    applePayInsertRequest.language = projectViewModel.isArabic ? 'ar' : 'en';
    applePayInsertRequest.languageID = projectViewModel.isArabic ? 1 : 2;
    applePayInsertRequest.userName = projectViewModel.authenticatedUserObject.user.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 = payfortProjectDetailsRespModel!.merchantIdentifier;
    applePayInsertRequest.commandType = "PURCHASE";
    applePayInsertRequest.signature = payfortProjectDetailsRespModel!.signature;
    applePayInsertRequest.accessCode = payfortProjectDetailsRespModel!.accessCode;
    applePayInsertRequest.shaRequestPhrase = payfortProjectDetailsRespModel!.shaRequest;
    applePayInsertRequest.shaResponsePhrase = payfortProjectDetailsRespModel!.shaResponse;
    applePayInsertRequest.returnURL = "";

    service.applePayInsertRequest(applePayInsertRequest, context).then((res) async {
      GifLoaderDialogUtils.hideDialog(context);
      if (res["MessageStatus"] == 1) {
        await context.read<PayfortViewModel>().initiateApplePayWithPayfort(
              customerName: projectViewModel.authenticatedUserObject.user.firstName! + " " + projectViewModel.authenticatedUserObject.user.lastName!,
              // customerEmail: projectViewModel.authenticatedUserObject.user.emailAddress,
              customerEmail: "CustID_${projectViewModel.authenticatedUserObject.user.patientID}@HMG.com",
              orderDescription: "Advance Payment",
              orderAmount: paymentAmount,
              merchantReference: transID,
              payfortProjectDetailsRespModel: payfortProjectDetailsRespModel,
              currency: projectViewModel.authenticatedUserObject.user.outSA == 1 ? "AED" : "SAR",
              onFailed: (failureResult) async {
                // GifLoaderDialogUtils.hideDialog(context);
                log("failureResult: ${failureResult.message.toString()}");
                AppToast.showErrorToast(message: failureResult.message.toString());
              },
              onSuccess: (successResult) async {
                // GifLoaderDialogUtils.hideDialog(context);
                GifLoaderDialogUtils.showMyDialog(context);
                log("Payfort: ${successResult.responseMessage}");
                await context.read<PayfortViewModel>().addPayfortApplePayResponse(projectViewModel.authenticatedUserObject.user.patientID!, result: successResult);
                await Future.delayed(Duration(milliseconds: 300));
                GifLoaderDialogUtils.hideDialog(context);
                await Future.delayed(Duration(milliseconds: 300));
                checkPaymentStatus(AppoitmentAllHistoryResultList());
              },
              projectId: selectedHospital!.iD,
              serviceTypeEnum: ServiceTypeEnum.advancePayment,
            );
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: "An error occurred while processing your request");
      }
    }).catchError((err) {
      print(err);
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
    });
  }

  openPayment(String paymentMethod, AuthenticatedUser authenticatedUser, num amount, AppoitmentAllHistoryResultList appo) {
    browser = new MyInAppBrowser(onExitCallback: onBrowserExit, appo: appo, onLoadStartCallback: onBrowserLoadStart);

    transID = Utils.getAdvancePaymentTransID(selectedHospital!.iD, projectViewModel.authenticatedUserObject.user.patientID!);

    browser.openPaymentBrowser(
        amount,
        "Advance Payment",
        transID,
        selectedHospital!.iD.toString(),
        projectViewModel.authenticatedUserObject.user.emailAddress!,
        paymentMethod,
        projectViewModel.authenticatedUserObject.user.patientType,
        "${projectViewModel.authenticatedUserObject.user.firstName} ${projectViewModel.authenticatedUserObject.user.lastName}",
        projectViewModel.authenticatedUserObject.user.patientID,
        authenticatedUser,
        browser,
        false,
        "3",
        "0",
        context,
        "",
        "",
        "",
        "",
        3);
  }

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

    if (selectedPaymentMethod == "TAMARA") {
      Uri uri = new Uri.dataFromString(url);
      tamaraPaymentStatus = uri.queryParameters['paymentStatus']!;
      tamaraOrderID = uri.queryParameters['orderId']!;
      print(tamaraPaymentStatus);
      print(tamaraOrderID);
    }

    MyInAppBrowser.successURLS.forEach((element) {
      if (url.contains(element)) {
        if (browser.isOpened()) browser.close();
        MyInAppBrowser.isPaymentDone = true;
        return;
      }
    });

    MyInAppBrowser.errorURLS.forEach((element) {
      if (url.contains(element)) {
        if (browser.isOpened()) browser.close();
        MyInAppBrowser.isPaymentDone = false;
        return;
      }
    });
  }

  onBrowserExit(AppoitmentAllHistoryResultList appo, bool isPaymentMade) {
    print("onBrowserExit Called");
    if (selectedPaymentMethod == "TAMARA" && tamaraPaymentStatus != null && tamaraPaymentStatus == "approved") {
      var res = {"Amount": paymentAmount, "ErrorMessage": null, "Fort_id": tamaraOrderID, "Merchant_Reference": "5058637919318707883366", "PaymentMethod": "TAMARA", "Response_Message": "Success"};
      purchaseOfferAPICall(res);
    } else {
      checkPaymentStatus(appo);
    }
  }

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    String txn_ref;
    String amount;
    String payment_method;
    final currency = projectViewModel.user!.outSA == 0 ? "sar" : 'aed';
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.checkPaymentStatus(transID, false, context).then((res) {
      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        txn_ref = res['Merchant_Reference'];
        amount = res['Amount'].toString();
        payment_method = res['PaymentMethod'];
        purchaseOfferAPICall(res);
      } else {
        GifLoaderDialogUtils.hideDialog(AppGlobal.context);
        AppToast.showErrorToast(message: res['Response_Message']);
        amount = paymentAmount.toString();
        payment_method = selectedPaymentMethod;
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  purchaseOfferAPICall(res) {
    DoctorsListService service = new DoctorsListService();
    String paymentReference = res['Fort_id'].toString();
    service.purchaseOfferAPICall(transID, selectedHospital!.iD!).then((res) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      if (res['MessageStatus'] == 1) {
        // AppToast.showSuccessToast(message: "Your payment has been made successfully");
        // Navigator.pop(context, true);

        AlertDialogBox(
            context: context,
            confirmMessage: projectViewModel.isArabic
                ? "تمت عملية الدفع بنجاح. بإمكانك زيارة ${selectedHospital!.nameN!} والإستفاده من العرض. نتمنى لك الصحة والعافية"
                : "Your payment has been successfully received. Please visit ${selectedHospital!.name!} to avail the offer. Wishing you good health & wellness.",
            okText: TranslationBase.of(context).ok,
            okFunction: () {
              AlertDialogBox.closeAlertDialog(context);
              Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => LandingPage()), (Route<dynamic> r) => false);
            }).showAlertDialog(context);
      } else {
        AppToast.showErrorToast(message: res['Message'] ?? "");
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  openHospitalSelection(BuildContext context) {
    var projectViewModel = Provider.of<ProjectViewModel>(context, listen: false);
    int _selectedHospitalIndex = 0;
    List<HospitalsModel> projectsListLocal = [];

    projectViewModel.hisProjectOffers.forEach((project) {
      projectsListLocal.add(new HospitalsModel(iD: project.projectId, name: project.projectEnglish, nameN: project.projectArabic, amountWithTax: project.amountWithTax));
    });

    showDialog(
      context: context,
      builder: (cxt) => LocationSelectionDialog(
        isArabic: projectViewModel.isArabic,
        data: projectsListLocal,
        title: TranslationBase.of(context).selectHospital,
        selectedIndex: _selectedHospitalIndex,
        onValueSelected: (index) {
          _selectedHospitalIndex = index;
          setState(() {
            selectedHospital = projectsListLocal[index];
            paymentAmount = projectsListLocal[index].amountWithTax ?? 295.0;
            print(paymentAmount);
          });
        },
      ),
    );
  }
}
