import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/enum/viewstate.dart';
import 'package:diplomaticquarterapp/core/model/my_balance/AdvanceModel.dart';
import 'package:diplomaticquarterapp/core/model/my_balance/patient_info_and_mobile_number.dart';
import 'package:diplomaticquarterapp/core/viewModels/medical/my_balance_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/apple_pay_request.dart';
import 'package:diplomaticquarterapp/models/apple_pay_response.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/otp/sms-popup.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:pay/pay.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;

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

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

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

  AppSharedPreferences sharedPref = AppSharedPreferences();

  String transID = "";

  Pay _payClient = Pay.withAssets([
    'applepay.json',
  ]);

  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") {
      //   startApplePay();
      // } else {
      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: Image.asset(getImagePath(widget.selectedPaymentMethod)),
                    ),
                    Text(
                      '${widget.advanceModel.amount} ' + TranslationBase.of(context).sar,
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.w900,
                        letterSpacing: -0.48,
                      ),
                    )
                  ],
                ),
                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(),
              () {
                projectViewModel.analytics.advancePayments.payment_confirm(method: widget.selectedPaymentMethod.toLowerCase(), type: 'wallet');

                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);
                });
                // 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);
                });
              },
            ),
          ),
        ),
      ),
    );
  }

  startApplePay() {
    GifLoaderDialogUtils.showMyDialog(context);
    ApplePayResponse applePayResponse;
    var _paymentItems = [
      PaymentItem(
        label: 'Total',
        amount: widget.advanceModel.amount,
        status: PaymentItemStatus.final_price,
      )
    ];

    _payClient.userCanPay(PayProvider.apple_pay).then((value) async {
      print(value);
      final result = await _payClient.showPaymentSelector(
        provider: PayProvider.apple_pay,
        paymentItems: _paymentItems,
      );
      print(result);
      applePayResponse = ApplePayResponse.fromJson(result);
      callPayfortApplePayAPI(applePayResponse);
    });
  }

  callPayfortApplePayAPI(ApplePayResponse applePayResponse) async {
    DoctorsListService service = new DoctorsListService();
    ApplePayRequest applePayRequest = new ApplePayRequest();
    AppleHeader appleHeader = new AppleHeader();
    ApplePaymentMethod applePaymentMethod = new ApplePaymentMethod();

    applePayRequest.amount = widget.advanceModel.amount;
    applePayRequest.currency = "SAR";
    applePayRequest.language = projectViewModel.isArabic ? "ar" : "en";
    applePayRequest.customername = projectViewModel.user.firstName;
    applePayRequest.customerEmail = projectViewModel.user.emailAddress;
    applePayRequest.orderdescription = "Advance Payment";
    applePayRequest.liveServiceid = "";
    applePayRequest.latitude = await this.sharedPref.getDouble(USER_LAT);
    applePayRequest.longitude = await this.sharedPref.getDouble(USER_LONG);
    applePayRequest.devicetoken = await sharedPref.getString(PUSH_TOKEN);
    applePayRequest.clientrequestid = Utils.getAdvancePaymentTransID(widget.advanceModel.hospitalsModel.iD, int.parse(widget.advanceModel.fileNumber));
    applePayRequest.projectid = widget.advanceModel.hospitalsModel.iD.toString();
    applePayRequest.serviceid = "3";
    applePayRequest.patientid = projectViewModel.user.patientID.toString();
    applePayRequest.appleData = applePayResponse.token.data;
    applePayRequest.appleSignature = applePayResponse.token.signature;

    appleHeader.appleEphemeralPublicKey = applePayResponse.token.header.ephemeralPublicKey;
    appleHeader.appleTransactionId = applePayResponse.token.header.transactionId;
    appleHeader.applePublicKeyHash = applePayResponse.token.header.publicKeyHash;
    applePaymentMethod.appleType = getApplePayPaymentType(applePayResponse.paymentMethod.type);
    applePaymentMethod.appleNetwork = applePayResponse.paymentMethod.network;
    applePaymentMethod.appleDisplayName = applePayResponse.paymentMethod.displayName;

    applePayRequest.appleHeader = appleHeader;
    applePayRequest.applePaymentMethod = applePaymentMethod;

    service.callPayfortApplePayAPI(applePayRequest, context).then((res) {
      print(res);
      GifLoaderDialogUtils.hideDialog(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      // _showMyDialog(err, this.context);
    });
  }

  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.png';
        break;
    }

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

  openPayment(String paymentMethod, AuthenticatedUser authenticatedUser, double 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", "");
  }

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

    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 (isPaymentMade) checkPaymentStatus(appo);
  }

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    DoctorsListService service = new DoctorsListService();
    service.checkPaymentStatus(transID, AppGlobal.context).then((res) {
      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        createAdvancePayment(res, appo);
      } else {
        GifLoaderDialogUtils.hideDialog(AppGlobal.context);
        AppToast.showErrorToast(message: 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(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) {
      print(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);
  }
}
