import 'package:diplomaticquarterapp/config/config.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/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.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/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/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

import 'dialogs/ConfirmSMSDialog.dart';
import 'new_text_Field.dart';

class ConfirmPaymentPage extends StatelessWidget {
  final AdvanceModel advanceModel;
  final PatientInfoAndMobileNumber patientInfoAndMobileNumber;
  final String selectedPaymentMethod;
  MyInAppBrowser browser;
  AuthenticatedUser authenticatedUser;
  AppSharedPreferences sharedPref = AppSharedPreferences();

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

  @override
  Widget build(BuildContext context) {
    void showSMSDialog() {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (cxt) => ConfirmSMSDialog(
          phoneNumber: patientInfoAndMobileNumber.mobileNumber,
        ),
      ).then((value) {
        print("dialog dismissed");
        print(value);
        if (value != null && value) {
          AppoitmentAllHistoryResultList appo =
              new AppoitmentAllHistoryResultList();
          appo.projectID = patientInfoAndMobileNumber.projectID;
          openPayment(selectedPaymentMethod, authenticatedUser,
              double.parse(advanceModel.amount), appo);
        }
      });
    }

    return BaseView<MyBalanceViewModel>(
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        appBarTitle: TranslationBase.of(context).advancePayment,
        body: SingleChildScrollView(
          physics: ScrollPhysics(),
          child: Container(
            margin: EdgeInsets.all(12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Texts(
                  TranslationBase.of(context).confirmThePayment,
                  textAlign: TextAlign.center,
                  fontWeight: FontWeight.w500,
                  fontSize: 24,
                ),
                SizedBox(
                  height: 12,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      height: 100.0,
                      padding: EdgeInsets.all(7.0),
                      width: MediaQuery.of(context).size.width * 0.45,
                      child: selectedPaymentMethod == "ApplePay" ? SvgPicture.asset(getImagePath(selectedPaymentMethod)) : Image.asset(getImagePath(selectedPaymentMethod)),
                    ),
                    Texts(
                      '${advanceModel.amount} SAR',
                      fontSize: 26,
                      bold: true,
                    )
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.all(3),
                        child: NewTextFields(
                          hintText: TranslationBase.of(context).fileNumber,
                          initialValue: advanceModel.fileNumber,
                          isEnabled: false,
                        ),
                      ),
                    ),
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.all(3),
                        child: NewTextFields(
                          hintText: TranslationBase.of(context).name,
                          initialValue: patientInfoAndMobileNumber.firstName,
                          isEnabled: false,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 12,
                ),
                NewTextFields(
                  hintText: TranslationBase.of(context).mobileNumber,
                  initialValue: patientInfoAndMobileNumber.mobileNumber,
                  isEnabled: false,
                ),
                SizedBox(
                  height: 12,
                ),
                NewTextFields(
                  hintText: TranslationBase.of(context).depositorName,
                  initialValue: advanceModel.depositorName,
                  isEnabled: false,
                ),
                SizedBox(
                  height: 12,
                ),
                NewTextFields(
                  hintText: TranslationBase.of(context).notes,
                  initialValue: advanceModel.note,
                  isEnabled: false,
                ),
              ],
            ),
          ),
        ),
        bottomSheet: Container(
          height: MediaQuery.of(context).size.height * 0.1,
          width: double.infinity,
          padding: EdgeInsets.all(12),
          child: SecondaryButton(
            textColor: Colors.white,
            label: TranslationBase.of(context).confirm.toUpperCase(),
            disabled: model.state == ViewState.Busy,
            onTap: () {
              GifLoaderDialogUtils.showMyDialog(context);
              model
                  .sendActivationCodeForAdvancePayment(
                      patientID: int.parse(advanceModel.fileNumber),
                      projectID: advanceModel.hospitalsModel.iD)
                  .then((value) {
                GifLoaderDialogUtils.hideDialog(context);
                if (model.state != ViewState.ErrorLocal &&
                    model.state != ViewState.Error) showSMSDialog();
              });
            },
          ),
        ),
      ),
    );
  }

  String getImagePath(String paymentMethod) {
    switch (paymentMethod) {
      case "MADA":
        return 'assets/images/new-design/mada.png';
        break;
      case "SADAD":
        return 'assets/images/new-design/sadad.png';
        break;
      case "VISA":
        return 'assets/images/new-design/visa.png';
        break;
      case "MASTERCARD":
        return 'assets/images/new-design/mastercard.png';
        break;
      case "Installment":
        return 'assets/images/new-design/installment.png';
        break;
      case "ApplePay":
        return 'assets/images/new-design/applepay.svg';
        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);

    browser.openPaymentBrowser(
        amount,
        "Advance Payment",
        Utils.getAdvancePaymentTransID(
            authenticatedUser.projectID, authenticatedUser.patientID),
        appo.projectID.toString(),
        authenticatedUser.emailAddress,
        paymentMethod,
        authenticatedUser.patientType,
        authenticatedUser.firstName,
        authenticatedUser.patientID,
        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) {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    service
        .checkPaymentStatus(
            Utils.getAppointmentTransID(
                appo.projectID, appo.clinicID, appo.appointmentNo),
            AppGlobal.context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      print("Printing Payment Status Reponse!!!!");
      print(res);
      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        createAdvancePayment(res, appo);
      } else {
        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();
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    service
        .createAdvancePayment(appo, appo.projectID.toString(), res['Amount'],
            res['Fort_id'], res['PaymentMethod'], AppGlobal.context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      print(res['OnlineCheckInAppointments'][0]['AdvanceNumber']);
      addAdvancedNumberRequest(
          res['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
          paymentReference,
          appo.appointmentNo.toString(),
          appo);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

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

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