import 'dart:developer';

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/enum/viewstate.dart';
import 'package:hmg_patient_app/core/model/my_balance/AdvanceModel.dart';
import 'package:hmg_patient_app/core/model/my_balance/patient_info_and_mobile_number.dart';
import 'package:hmg_patient_app/core/viewModels/medical/my_balance_view_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/models/apple_pay_request.dart';
import 'package:hmg_patient_app/models/apple_pay_response.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/routes.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/theme/colors.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/defaultButton.dart';
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/otp/sms-popup.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import 'new_text_Field.dart';

class ConfirmPaymentPage extends StatefulWidget {
  final AdvanceModel? advanceModel;
  final PatientInfoAndMobileNumber? patientInfoAndMobileNumber;
  final String? selectedPaymentMethod;
  AuthenticatedUser? authenticatedUser;
  String? installmentPlan;

  ConfirmPaymentPage({this.advanceModel, this.patientInfoAndMobileNumber, this.selectedPaymentMethod, this.authenticatedUser, this.installmentPlan});

  @override
  _ConfirmPaymentPageState createState() => _ConfirmPaymentPageState();
}

class _ConfirmPaymentPageState extends State<ConfirmPaymentPage> {
  late MyInAppBrowser browser;
  late ProjectViewModel projectViewModel;

  AppSharedPreferences sharedPref = AppSharedPreferences();

  String transID = "";

  late String tamaraPaymentStatus;
  late String tamaraOrderID;

  // Pay _payClient;

  @override
  void initState() {
    // _payClient = Pay.withAssets([
    //   'applepay.json',
    // ]);
    super.initState();
  }

  void submit(MyBalanceViewModel model, code) {
    final activationCode = code;
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    model.checkActivationCodeForAdvancePayment(activationCode: activationCode).then((value) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      Navigator.pop(context, true);
      AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
      appo.projectID = widget.patientInfoAndMobileNumber!.projectID;

      if (widget.selectedPaymentMethod == "ApplePay") {
        if (projectViewModel.havePrivilege(103)) {
          startApplePay();
        } else {
          openPayment(widget.selectedPaymentMethod!, widget.authenticatedUser!, double.parse(widget.advanceModel!.amount!), AppoitmentAllHistoryResultList());
        }
      } else {
        openPayment(widget.selectedPaymentMethod!, widget.authenticatedUser!, double.parse(widget.advanceModel!.amount!), AppoitmentAllHistoryResultList());
      }

      projectViewModel.analytics.advancePayments.payment_otp_confirmation(method: widget.selectedPaymentMethod!.toLowerCase(), type: 'wallet');
      // openPayment(widget.selectedPaymentMethod, widget.authenticatedUser, double.parse(widget.advanceModel.amount), null);
    });
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    void showSMSDialog(MyBalanceViewModel model) {
      new SMSOTP(
        context,
        1,
        widget.patientInfoAndMobileNumber!.mobileNumber,
        (value) {
          submit(model, value);
        },
        () => {
          Navigator.pop(context),
        },
      ).displayDialog(context);
    }

    projectViewModel = Provider.of(context);
    return BaseView<MyBalanceViewModel>(
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        appBarTitle: TranslationBase.of(context).advancePayment,
        showNewAppBarTitle: true,
        showNewAppBar: true,
        backgroundColor: CustomColors.appBackgroudGreyColor,
        body: SingleChildScrollView(
          physics: ScrollPhysics(),
          child: Container(
            margin: EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  TranslationBase.of(context).confirmThePayment,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                    letterSpacing: -0.48,
                  ),
                ),
                SizedBox(
                  height: 12,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      height: 100.0,
                      padding: EdgeInsets.all(7.0),
                      width: MediaQuery.of(context).size.width * 0.30,
                      child: widget.selectedPaymentMethod == "ApplePay"
                          ? SvgPicture.asset(
                              getImagePath(widget.selectedPaymentMethod!),
                            )
                          : Image.asset(getImagePath(widget.selectedPaymentMethod!)),
                    ),
                    Row(
                      children: [
                        widget.advanceModel!.hospitalsModel!.projectOutSA! ? Container() : projectViewModel.isArabic ? Container() : SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 20, height: 20),
                        mWidth(6),
                        Text(
                          widget.advanceModel!.hospitalsModel!.projectOutSA! ? '${widget.advanceModel!.amount} ' + TranslationBase.of(context).aed : '${widget.advanceModel!.amount}',
                          // '${widget.advanceModel.amount} ' + TranslationBase.of(context).sar,
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.w900,
                            letterSpacing: -0.48,
                          ),
                        ),
                        mWidth(6),
                        widget.advanceModel!.hospitalsModel!.projectOutSA! ? Container() : projectViewModel.isArabic ? SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 20, height: 20) : Container(),
                      ],
                    )
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.all(3),
                        child: NewTextFields(
                          hintText: TranslationBase.of(context).fileNumber,
                          initialValue: widget.advanceModel!.fileNumber!,
                          isEnabled: false,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.all(3),
                        child: NewTextFields(
                          hintText: TranslationBase.of(context).name,
                          initialValue: widget.patientInfoAndMobileNumber!.firstName!,
                          isEnabled: false,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                NewTextFields(
                  hintText: TranslationBase.of(context).mobileNumber,
                  initialValue: widget.patientInfoAndMobileNumber!.mobileNumber!,
                  isEnabled: false,
                ),
                SizedBox(
                  height: 12,
                ),
                NewTextFields(
                  hintText: TranslationBase.of(context).depositorName,
                  initialValue: model.user!.firstName! + " " + model.user!.middleName! + " " + model.user!.lastName!,
                  isEnabled: false,
                ),
                SizedBox(
                  height: 12,
                ),
                NewTextFields(
                  hintText: TranslationBase.of(context).notes,
                  initialValue: widget.advanceModel!.note!,
                  isEnabled: false,
                ),
              ],
            ),
          ),
        ),
        bottomSheet: Container(
          color: Colors.white,
          child: Container(
            // height: MediaQuery.of(context).size.width * 0.18,
            width: double.infinity,
            padding: EdgeInsets.all(20),
            child: DefaultButton(
              TranslationBase.of(context).confirm.toUpperCase(),
              () async {
                if (widget.advanceModel!.fileNumber == projectViewModel.user.patientID.toString()) {
                  if (widget.selectedPaymentMethod == "ApplePay") {
                    if (projectViewModel.havePrivilege(103)) {
                      startApplePay();
                    } else {
                      openPayment(widget.selectedPaymentMethod!, widget.authenticatedUser!, double.parse(widget.advanceModel!.amount!), AppoitmentAllHistoryResultList());
                    }
                  } else {
                    openPayment(widget.selectedPaymentMethod!, widget.authenticatedUser!, double.parse(widget.advanceModel!.amount!), AppoitmentAllHistoryResultList());
                  }
                } else {
                  GifLoaderDialogUtils.showMyDialog(context);
                  model.sendActivationCodeForAdvancePayment(patientID: int.parse(widget.advanceModel!.fileNumber!), projectID: widget.advanceModel!.hospitalsModel!.iD).then((value) {
                    GifLoaderDialogUtils.hideDialog(context);
                    if (model.state != ViewState.ErrorLocal && model.state != ViewState.Error) showSMSDialog(model);
                  });
                }
                projectViewModel.analytics.advancePayments.payment_confirm(method: widget.selectedPaymentMethod!.toLowerCase(), type: 'wallet');

                // startApplePay();
                // if()
                // GifLoaderDialogUtils.showMyDialog(context);
                // model.sendActivationCodeForAdvancePayment(patientID: int.parse(widget.advanceModel.fileNumber), projectID: widget.advanceModel.hospitalsModel.iD).then((value) {
                //   GifLoaderDialogUtils.hideDialog(context);
                //   if (model.state != ViewState.ErrorLocal && model.state != ViewState.Error) showSMSDialog(model);
                // });
              },
            ),
          ),
        ),
      ),
    );
  }

  void startApplePay() async {
    transID = Utils.getAdvancePaymentTransID(widget.advanceModel!.hospitalsModel!.iD!, int.parse(widget.advanceModel!.fileNumber!));
    print("TransactionID: $transID");
    GifLoaderDialogUtils.showMyDialog(context);

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

    PayfortProjectDetailsRespModel? payfortProjectDetailsRespModel;
    await context
        .read<PayfortViewModel>()
        .getProjectDetailsForPayfort(projectId: widget.advanceModel!.hospitalsModel!.iD, serviceId: ServiceTypeEnum.advancePayment.getIdFromServiceEnum())
        .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_${widget.advanceModel!.fileNumber}@HMG.com";
    applePayInsertRequest.customerID = widget.advanceModel!.fileNumber;
    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 = widget.advanceModel!.hospitalsModel!.iD.toString();
    applePayInsertRequest.serviceID = ServiceTypeEnum.advancePayment.getIdFromServiceEnum().toString();
    applePayInsertRequest.channelID = 3;
    applePayInsertRequest.patientID = widget.advanceModel!.fileNumber;
    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 = widget.advanceModel!.amount.toString();
    applePayInsertRequest.isSchedule = "0";
    applePayInsertRequest.language = projectViewModel.isArabic ? 'ar' : 'en';
    applePayInsertRequest.languageID = projectViewModel.isArabic ? 1 : 2;
    applePayInsertRequest.userName = int.parse(widget.advanceModel!.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 = 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 {
      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_${widget.advanceModel!.fileNumber!}@HMG.com",
              orderDescription: "Advance Payment",
              orderAmount: double.parse(widget.advanceModel!.amount!),
              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 {
                log("Payfort: ${successResult.responseMessage}");
                await context.read<PayfortViewModel>().addPayfortApplePayResponse(num.parse(widget.advanceModel!.fileNumber!), result: successResult);
                checkPaymentStatus(AppoitmentAllHistoryResultList());
              },
              projectId: widget.advanceModel!.hospitalsModel!.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);
    });
  }

  String getApplePayPaymentType(dynamic paymentMethod) {
    switch (paymentMethod) {
      case 1:
        return 'debit';
        break;
      case 2:
        return 'credit';
        break;
      case 3:
        return 'prepaid';
        break;
    }
    return 'debit';
  }

  String getImagePath(String paymentMethod) {
    switch (paymentMethod) {
      case "MADA":
        return 'assets/images/new/payment/Mada.png';
        break;
      case "SADAD":
        return 'assets/images/new-design/sadad.png';
        break;
      case "VISA":
        return 'assets/images/new/payment/visa.png';
        break;
      case "MASTERCARD":
        return 'assets/images/new/payment/Mastercard.png';
        break;
      case "Installment":
        return 'assets/images/new/payment/installments.png';
        break;
      case "ApplePay":
        return 'assets/images/new/payment/Apple_Pay.svg';
        // return 'assets/images/new/payment/Apple_Pay.png';
        break;
      case "TAMARA":
        return 'assets/images/new/payment/tamara.png';
        break;
    }

    return 'assets/images/new-design/mada.png';
  }

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

    transID = Utils.getAdvancePaymentTransID(widget.advanceModel!.hospitalsModel!.iD, int.parse(widget.advanceModel!.fileNumber!));

    browser.openPaymentBrowser(
        amount,
        "Advance Payment",
        transID,
        widget.advanceModel!.hospitalsModel!.iD.toString(),
        widget.advanceModel!.email!,
        paymentMethod,
        widget.patientInfoAndMobileNumber!.patientType,
        widget.advanceModel!.patientName!,
        widget.advanceModel!.fileNumber!,
        authenticatedUser,
        browser,
        false,
        "3",
        "0",
        context,
        "",
        "",
        "",
        "",
        widget.installmentPlan);
  }

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

    if (widget.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 (widget.selectedPaymentMethod == "TAMARA" && tamaraPaymentStatus != null && tamaraPaymentStatus == "approved") {
      var res = {
        "Amount": double.parse(widget.advanceModel!.amount!),
        "ErrorMessage": null,
        "Fort_id": tamaraOrderID,
        "Merchant_Reference": "5058637919318707883366",
        "PaymentMethod": "TAMARA",
        "Response_Message": "Success"
      };
      createAdvancePayment(res, appo);
    } else {
      checkPaymentStatus(appo);
    }
  }

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    String txn_ref;
    String amount;
    String payment_method;
    final currency = projectViewModel.user!.outSA == 0 ? "sar" : 'aed';
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    DoctorsListService service = new DoctorsListService();
    service.checkPaymentStatus(transID, false, AppGlobal.context).then((res) {
      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        txn_ref = res['Merchant_Reference'];
        amount = res['Amount'].toString();
        payment_method = res['PaymentMethod'];
        createAdvancePayment(res, appo);
        projectViewModel.analytics.advancePayments.payment_success(
            payment_type: 'wallet', payment_method: payment_method, txn_amount: "$amount", txn_currency: currency, txn_number: txn_ref, hospital: widget.advanceModel!.hospitalsModel!.name!);
      } else {
        GifLoaderDialogUtils.hideDialog(AppGlobal.context);
        AppToast.showErrorToast(message: res['Response_Message']);
        amount = widget.advanceModel!.amount!;
        payment_method = widget.selectedPaymentMethod!;
        projectViewModel.analytics.advancePayments.payment_fail(
            payment_type: 'wallet',
            payment_method: payment_method,
            txn_amount: "$amount",
            txn_currency: currency,
            hospital: widget.advanceModel!.hospitalsModel!.name!,
            error_type: res['Response_Message']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  createAdvancePayment(res, AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    String paymentReference = res['Fort_id'].toString();
    service.HIS_createAdvancePayment(appo, widget.advanceModel!.hospitalsModel!.iD.toString(), res['Amount'], res['Fort_id'], res['PaymentMethod'], widget.patientInfoAndMobileNumber!.patientType,
            widget.advanceModel!.patientName!, widget.advanceModel!.fileNumber, AppGlobal.context)
        .then((res) {
      addAdvancedNumberRequest(
          Utils.isVidaPlusProject(projectViewModel, widget.advanceModel!.hospitalsModel!.iD)
              ? res['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString()
              : res['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
          paymentReference,
          0,
          appo);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  addAdvancedNumberRequest(String advanceNumber, String paymentReference, dynamic appointmentID, AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    service.addAdvancedNumberRequest(advanceNumber, paymentReference, appointmentID, AppGlobal.context).then((res) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      navigateToHome(AppGlobal.context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  Future navigateToHome(context) async {
    Navigator.of(context).pushNamed(HOME);
  }
}
