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

import 'package:diplomaticquarterapp/core/enum/PayfortEnums.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Appointments/PatientShareResposne.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/LiveCare/ApplePayInsertRequest.dart';
import 'package:diplomaticquarterapp/models/header_model.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/payment_method_select.dart';
import 'package:diplomaticquarterapp/pages/insurance/insurance_update_screen.dart';
import 'package:diplomaticquarterapp/pages/landing/landing_page.dart';
import 'package:diplomaticquarterapp/routes.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/livecare_services/livecare_provider.dart';
import 'package:diplomaticquarterapp/services/payfort_services/payfort_project_details_resp_model.dart';
import 'package:diplomaticquarterapp/services/payfort_services/payfort_view_model.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/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/custom_text_button.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/new_design/doctor_header.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../config/shared_pref_kay.dart';
import 'QRCode.dart';

class BookSuccess extends StatefulWidget {
  PatientShareResponse patientShareResponse;
  DoctorList docObject;

  late MyInAppBrowser browser;
  // final ChromeSafariBrowser chromeBrowser = new MyChromeSafariBrowser(new MyInAppBrowser());

  String appoDateFormatted;
  String appoTimeFormatted;
  bool isCash = false;

  BookSuccess({required this.patientShareResponse, required this.docObject, required this.appoDateFormatted, required this.appoTimeFormatted, this.isCash = false});

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

class _BookSuccessState extends State<BookSuccess> {
  AppSharedPreferences sharedPref = AppSharedPreferences();

  // AuthenticatedUser authUser;

  late ProjectViewModel projectViewModel;
  String? selectedPaymentMethod = "";
  String? selectedInstallments = "";
  String? tamaraPaymentStatus;
  String? tamaraOrderID;
  String? transID;

  @override
  initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (widget.patientShareResponse.isLiveCareAppointment! &&
          (widget.patientShareResponse.patientShareWithTax.toString() == "0" || widget.patientShareResponse.patientShareWithTax.toString() == "0.0")) {
        setOnlineCheckInForAppointment();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of<ProjectViewModel>(context);
    return AppScaffold(
      appBarTitle: widget.docObject.doctorTitle! + " " + widget.docObject.name!,
      isShowDecPage: false,
      isShowAppBar: true,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      backgroundColor: CustomColors.appBackgroudGreyColor,
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            DoctorHeader(
              headerModel: HeaderModel(
                widget.docObject.name!,
                widget.docObject.doctorID!,
                widget.docObject.doctorImageURL!,
                widget.docObject.speciality!,
                "",
                widget.docObject.projectName!,
                null,
                null,
                widget.docObject.nationalityFlagURL ?? "",
                widget.docObject.doctorRate,
                null,
                widget.docObject.noOfPatientsRate,
                "",
              ),
              isNeedToShowButton: false,
            ),
            Container(
              alignment: Alignment.center,
              color: CustomColors.green,
              child: Table(
                border: TableBorder(verticalInside: BorderSide(width: 0.5, color: Colors.white)),
                children: [
                  TableRow(
                    children: [
                      TableCell(child: _getNormalText(TranslationBase.of(context).patientShare)),
                      TableCell(child: _getNormalText(TranslationBase.of(context).patientShareWithTax)),
                    ],
                  ),
                  TableRow(
                    children: [
                      TableCell(child: _getHeadingText("SR " + widget.patientShareResponse.patientShare.toString())),
                      TableCell(child: _getHeadingText("SR " + widget.patientShareResponse.patientShareWithTax.toString())),
                    ],
                  ),
                ],
              ),
            ),
            getNextActionWidget()!,
          ],
        ),
      ),
      bottomSheet: getBottomContainer(),
    );
  }

  Widget? getBottomContainer() {
    switch (widget.patientShareResponse.nextAction) {
      case 0:
        return Container();
        break;
      case 10:
        return _getConfirmAppoButtons();
        break;
      case 15:
        return _getPaymentPendingAppo();
        break;
      case 20:
        return _getPayNowButtons();
        break;
      case 30:
        return _getQRButtons();
        break;
      case 50:
        return _getConfirmAppoButtons();
        break;
      case 90:
        return _getQRButtons();
    }
  }

  Widget _getQRButtons() {
    return Container(
      alignment: Alignment.bottomCenter,
      margin: EdgeInsets.all(14),
      height: MediaQuery.of(context).size.height * 0.18,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Row(
            children: [
              Expanded(
                flex: 1,
                child: ButtonTheme(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  minWidth: MediaQuery.of(context).size.width * 0.7,
                  height: 45.0,
                  child: CustomTextButton(
                    backgroundColor: CustomColors.green,
                    elevation: 0,
                    onPressed: () {
                      GifLoaderDialogUtils.showMyDialog(context);
                      getAppoQR(context);
                    },
                    child: Text(TranslationBase.of(context).checkinOptions, style: TextStyle(fontSize: 18.0, color: Colors.white)),
                  ),
                ),
              ),
              mWidth(7),
              Expanded(
                flex: 1,
                child: ButtonTheme(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  minWidth: MediaQuery.of(context).size.width * 0.7,
                  height: 45.0,
                  child: CustomTextButton(
                    backgroundColor: Color(0xffc5272d),
                    elevation: 0,
                    onPressed: () {
                      navigateToHome(context);
                      // GifLoaderDialogUtils.showMyDialog(context);
                      // getAppoQR(context);
                    },
                    child: Text(TranslationBase.of(context).done, style: TextStyle(fontSize: 18.0, color: Colors.white)),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _getPayNowButtons() {
    return Container(
      color: CustomColors.appBackgroudGreyColor,
      child: Container(
        color: CustomColors.appBackgroudGreyColor,
        margin: EdgeInsets.all(14),
        height: widget.isCash ? 150.0 : 50,
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: ButtonTheme(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    height: 45.0,
                    child: CustomTextButton(
                      backgroundColor: CustomColors.green,
                      elevation: 0,
                      onPressed: () {
                        startPaymentProcess();
                        projectViewModel.analytics.appointment.pay_now_for_appointment(appointment_type: 'regular', doctorDetail: widget.docObject, payNow: true);
                      },
                      child: Text(TranslationBase.of(context).payNow.toUpperCase(),
                          style: TextStyle(
                            fontSize: 18.0,
                            color: Colors.white,
                          )),
                    ),
                  ),
                ),
                mWidth(7),
                Expanded(
                  flex: 1,
                  child: ButtonTheme(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    height: 45.0,
                    child: CustomTextButton(
                      backgroundColor: Color(0xffc5272d),
                      elevation: 0,
                      onPressed: () {
                        navigateToHome(context);
                        projectViewModel.analytics.appointment.pay_now_for_appointment(appointment_type: 'regular', doctorDetail: widget.docObject, payNow: false);
                      },
                      child: Text(TranslationBase.of(context).payLater.toUpperCase(), style: TextStyle(fontSize: 18.0, color: Colors.white)),
                    ),
                  ),
                ),
              ],
            ),
            widget.isCash
                ? Column(
                    children: [
                      mHeight(10.0),
                      Text(
                        TranslationBase.of(context).cashAmountUpdateInsurance,
                        style: TextStyle(
                          fontSize: 14.0,
                          fontWeight: FontWeight.w600,
                          color: Color(0xff2E303A),
                        ),
                      ),
                      mHeight(5.0),
                      DefaultButton(
                        TranslationBase.of(context).updateInsuranceText,
                        () {
                          Navigator.pop(context, null);
                          Navigator.pushAndRemoveUntil(
                            context,
                            MaterialPageRoute(builder: (context) => LandingPage()),
                            (Route<dynamic> route) => false,
                          );
                          Navigator.push(context, FadePage(page: InsuranceUpdate()));
                        },
                        color: Color(0xffEAA118),
                        textColor: Colors.white,
                      ),
                    ],
                  )
                : Container(),
          ],
        ),
      ),
    );
  }

  Widget _getConfirmAppoButtons() {
    return Container(
      color: CustomColors.appBackgroudGreyColor,
      child: Container(
        color: CustomColors.appBackgroudGreyColor,
        margin: EdgeInsets.all(14),
        height: 45.0,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            Expanded(
              flex: 1,
              child: ButtonTheme(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                height: 45.0,
                child: CustomTextButton(
                  backgroundColor: Color(0xffc5272d),
                  elevation: 0,
                  onPressed: () {
                    AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
                    appo.clinicID = widget.docObject.clinicID;
                    appo.projectID = widget.docObject.projectID;
                    appo.appointmentNo = widget.patientShareResponse.appointmentNo;
                    appo.serviceID = widget.patientShareResponse.serviceID;
                    appo.isLiveCareAppointment = widget.patientShareResponse.isLiveCareAppointment;
                    appo.doctorID = widget.patientShareResponse.doctorID;
                    appo.appointmentDate = widget.patientShareResponse.appointmentDate;
                    if (appo.isLiveCareAppointment!)
                      insertLiveCareVIDARequest(appo);
                    else
                      navigateToHome(context);
                  },
                  child: Text(TranslationBase.of(context).confirmLater, style: TextStyle(fontSize: 16.0, color: Colors.white)),
                ),
              ),
            ),
            mWidth(7),
            Expanded(
              flex: 1,
              child: ButtonTheme(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                height: 45.0,
                child: CustomTextButton(
                  backgroundColor: CustomColors.green,
                  elevation: 0,
                  onPressed: () {
                    AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
                    appo.clinicID = widget.docObject.clinicID;
                    appo.projectID = widget.docObject.projectID;
                    appo.appointmentNo = widget.patientShareResponse.appointmentNo;
                    appo.serviceID = widget.patientShareResponse.serviceID;
                    appo.isLiveCareAppointment = widget.patientShareResponse.isLiveCareAppointment;
                    appo.doctorID = widget.patientShareResponse.doctorID;
                    if (appo.isLiveCareAppointment!) {
                      navigateToHome(context);
                    } else {
                      confirmAppointment(appo);
                    }
                  },
                  child: Text(widget.patientShareResponse.isLiveCareAppointment! ? TranslationBase.of(context).confirmLiveCare : TranslationBase.of(context).confirm,
                      style: TextStyle(fontSize: 16.0, color: Colors.white)),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget? getNextActionWidget() {
    switch (widget.patientShareResponse.nextAction) {
      case 0:
        return Container();
        break;
      case 10:
        return _getConfirmAppo();
        break;
      case 15:
        return _getPaymentPendingAppo();
        break;
      case 20:
        return _getPayNowAppo();
        break;
      case 30:
        return _getQRAppo();
        break;
      case 50:
        return _getConfirmAppo();
        break;
      case 90:
        return _getQRAppo();
    }
  }

  String? getNextAction() {
    switch (widget.patientShareResponse.nextAction) {
      case 0:
        return 'No Action';
        break;
      case 10:
        return 'Confirm';
        break;
      case 15:
        return 'Payment Pending';
        break;
      case 20:
        return 'Pay Now';
        break;
      case 30:
        return 'QR Code';
        break;
      case 50:
        return 'Confirm LiveCare';
        break;
      case 90:
        return 'QR Code';
        break;
    }
  }

  Widget _getConfirmAppo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 30.0, bottom: 40.0),
          alignment: Alignment.center,
          child: Text(TranslationBase.of(context).confirmAppo, style: TextStyle(fontSize: 18.0, letterSpacing: 0.8)),
        ),
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    _getBulletPoint("1"),
                    Container(
                      width: MediaQuery.of(context).size.width * 0.8,
                      child: Text(TranslationBase.of(context).upcomingConfirm, overflow: TextOverflow.clip, style: TextStyle(fontSize: 13.0)),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(top: 20.0, left: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    _getBulletPoint("2"),
                    Container(
                      width: MediaQuery.of(context).size.width * 0.8,
                      child: Text(TranslationBase.of(context).upcomingConfirmMore, overflow: TextOverflow.clip, style: TextStyle(fontSize: 13.0)),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        Container(margin: EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 5.0), child: getPaymentMethods()),
      ],
    );
  }

  Widget _getPaymentPendingAppo() {
    return Container();
  }

  setOnlineCheckInForAppointment() {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.setOnlineCheckInForAppointment(widget.patientShareResponse.appointmentNo.toString(), widget.patientShareResponse.projectID!, projectViewModel.isArabic ? 1 : 2, context).then((res) {
      AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
      appo.clinicID = widget.docObject.clinicID;
      appo.projectID = widget.docObject.projectID;
      appo.appointmentNo = widget.patientShareResponse.appointmentNo;
      appo.serviceID = widget.patientShareResponse.serviceID;
      appo.isLiveCareAppointment = widget.patientShareResponse.isLiveCareAppointment;
      appo.doctorID = widget.patientShareResponse.doctorID;
      appo.appointmentDate = widget.patientShareResponse.appointmentDate;
      insertLiveCareVIDARequest(appo, isMoveHome: false);
      GifLoaderDialogUtils.hideDialog(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  confirmAppointment(AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.confirmAppointment(appo.appointmentNo!, appo.clinicID!, appo.projectID!, appo.isLiveCareAppointment!, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
        if (appo.isLiveCareAppointment!) {
          insertLiveCareVIDARequest(appo);
        } else {
          navigateToHome(context);
        }
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  insertLiveCareVIDARequest(AppoitmentAllHistoryResultList appo, {bool isMoveHome = true}) {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service
        .insertVIDARequest(appo.appointmentNo, appo.clinicID, appo.projectID, appo.serviceID, appo.doctorID, appo.appointmentDate!,
            Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), projectViewModel.isArabic ? 1 : 2, context)
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        if (isMoveHome) navigateToHome(context);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  Widget _getPayNowAppo() {
    return Padding(
      padding: const EdgeInsets.only(left: 20, right: 20, top: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          Text(
            TranslationBase.of(context).payNowBookSuccess,
            style: TextStyle(
              fontSize: 24.0,
              letterSpacing: -1.44,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            TranslationBase.of(context).neverWait,
            style: TextStyle(
              fontSize: 12.0,
              letterSpacing: -0.54,
              fontWeight: FontWeight.w600,
            ),
          ),
          mHeight(24),
          Text(TranslationBase.of(context).payNowBookSuccesstext1,
              overflow: TextOverflow.fade,
              style: TextStyle(
                fontSize: 12.0,
                letterSpacing: -0.36,
              )),
          Container(margin: EdgeInsets.fromLTRB(20.0, 5.0, 20.0, 5.0), child: getPaymentMethods()),
          Text(
            TranslationBase.of(context).payNowBookSuccesstext2,
            overflow: TextOverflow.clip,
            style: TextStyle(
              fontSize: 12.0,
              letterSpacing: -0.36,
            ),
          ),
        ],
      ),
    );
  }

  startPaymentProcess() {
    navigateToPaymentMethod(context, widget.patientShareResponse);
  }

  Future navigateToPaymentMethod(context, PatientShareResponse patientShareResponse) async {
    AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
    appo.projectID = widget.patientShareResponse.projectID;
    appo.clinicID = widget.patientShareResponse.clinicID;
    appo.clinicName = widget.patientShareResponse.clinicName;
    appo.projectName = widget.patientShareResponse.projectName;
    appo.appointmentNo = widget.patientShareResponse.appointmentNo;
    appo.isLiveCareAppointment = widget.patientShareResponse.isLiveCareAppointment;
    appo.doctorID = widget.patientShareResponse.doctorID;
    appo.appointmentDate = widget.patientShareResponse.appointmentDate;
    appo.serviceID = widget.patientShareResponse.serviceID;

    Navigator.push(
            context,
            FadePage(
                page: PaymentMethod(
                    onSelectedMethod: (String metohd, [String? selectedInstallmentPlan]) {
                      setState(() {});
                    },
                    patientShare: widget.patientShareResponse.patientShareWithTax)))
        .then((value) {
      selectedPaymentMethod = value[0];
      if (value != null) {
        if (selectedPaymentMethod == "ApplePay") {
          if (projectViewModel.havePrivilege(103)) {
            startApplePay(appo, patientShareResponse);
          } else {
            openPayment(value, projectViewModel.user, double.parse(patientShareResponse.patientShareWithTax.toString()), patientShareResponse, appo);
          }
        } else {
          openPayment(value, projectViewModel.user, double.parse(patientShareResponse.patientShareWithTax.toString()), patientShareResponse, appo);
        }
        projectViewModel.analytics.appointment.payment_method(appointment_type: 'regular', clinic: widget.docObject.clinicName, payment_method: value[0], payment_type: 'appointment');
      }
    });
  }

  void startApplePay(AppoitmentAllHistoryResultList appo, PatientShareResponse patientShareResponse) async {
    transID = Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo);
    print("TransactionID: $transID");
    GifLoaderDialogUtils.showMyDialog(context);

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

    PayfortProjectDetailsRespModel? payfortProjectDetailsRespModel;
    await context.read<PayfortViewModel>().getProjectDetailsForPayfort(projectId: appo.projectID, serviceId: ServiceTypeEnum.appointmentPayment.getIdFromServiceEnum()).then((value) {
      payfortProjectDetailsRespModel = value!;
    });

    applePayInsertRequest.clientRequestID = transID;
    applePayInsertRequest.clinicID = appo.clinicID;
    applePayInsertRequest.currency = projectViewModel.user.outSA == 1 ? "AED" : "SAR";
    // applePayInsertRequest.customerEmail = projectViewModel.authenticatedUserObject.user.emailAddress;
    applePayInsertRequest.customerEmail = "CustID_${projectViewModel.user.patientID}@HMG.com";
    applePayInsertRequest.customerID = projectViewModel.user.patientID;
    applePayInsertRequest.customerName = projectViewModel.user.firstName! + " " + projectViewModel.user.lastName!;
    applePayInsertRequest.deviceToken = await AppSharedPreferences().getString(PUSH_TOKEN);
    applePayInsertRequest.voipToken = await AppSharedPreferences().getString(ONESIGNAL_APNS_TOKEN);
    applePayInsertRequest.doctorID = appo.doctorID;
    applePayInsertRequest.projectID = appo.projectID.toString();
    applePayInsertRequest.serviceID = ServiceTypeEnum.appointmentPayment.getIdFromServiceEnum().toString();
    applePayInsertRequest.channelID = 3;
    applePayInsertRequest.patientID = projectViewModel.user.patientID;
    applePayInsertRequest.patientTypeID = projectViewModel.user.patientType;
    applePayInsertRequest.patientOutSA = projectViewModel.user.outSA;
    applePayInsertRequest.appointmentDate = appo.appointmentDate;
    applePayInsertRequest.appointmentNo = appo.appointmentNo;
    applePayInsertRequest.orderDescription = "Appointment Payment";
    applePayInsertRequest.liveServiceID = "0";
    applePayInsertRequest.latitude = "0.0";
    applePayInsertRequest.longitude = "0.0";
    applePayInsertRequest.amount = patientShareResponse.patientShareWithTax.toString();
    applePayInsertRequest.isSchedule = appo.isLiveCareAppointment! ? "1" : "0";
    applePayInsertRequest.language = projectViewModel.isArabic ? 'ar' : 'en';
    applePayInsertRequest.languageID = projectViewModel.isArabic ? 1 : 2;
    applePayInsertRequest.userName = projectViewModel.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 {
      if (res["MessageStatus"] == 1) {
        await context.read<PayfortViewModel>().initiateApplePayWithPayfort(
              customerName: projectViewModel.user.firstName! + " " + projectViewModel.user.lastName!,
              // customerEmail: projectViewModel.authenticatedUserObject.user.emailAddress,
              customerEmail: "CustID_${projectViewModel.user.patientID}@HMG.com",
              orderDescription: "Appointment Payment",
              orderAmount: double.parse(patientShareResponse.patientShareWithTax.toString()),
              merchantReference: transID,
              payfortProjectDetailsRespModel: payfortProjectDetailsRespModel,
              currency: projectViewModel.user.outSA == 1 ? "AED" : "SAR",
              onFailed: (failureResult) async {
                GifLoaderDialogUtils.hideDialog(context);
                log("failureResult: ${failureResult.toString()}");
                AppToast.showErrorToast(message: failureResult.toString());
              },
              onSuccess: (successResult) async {
                log("Payfort: ${successResult.responseMessage}");
                await context.read<PayfortViewModel>().addPayfortApplePayResponse(projectViewModel.user.patientID!, result: successResult);
                checkPaymentStatus(appo);
              },
              projectId: appo.projectID,
              serviceTypeEnum: ServiceTypeEnum.appointmentPayment,
            );
      } 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(List<String?> paymentMethod, AuthenticatedUser authenticatedUser, num amount, PatientShareResponse patientShareResponse, AppoitmentAllHistoryResultList appo) async {
    widget.browser = new MyInAppBrowser(onExitCallback: onBrowserExit, appo: appo, onLoadStartCallback: onBrowserLoadStart, context: context);
    selectedPaymentMethod = paymentMethod[0];
    selectedInstallments = paymentMethod[1];
    transID = Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo);
    widget.browser.openPaymentBrowser(
        amount,
        "Appointment check in",
        transID!,
        appo.projectID.toString(),
        authenticatedUser.emailAddress!,
        paymentMethod[0]!,
        authenticatedUser.patientType,
        authenticatedUser.firstName!,
        authenticatedUser.patientID,
        authenticatedUser,
        widget.browser,
        widget.patientShareResponse.isLiveCareAppointment!,
        "2",
        widget.patientShareResponse.isLiveCareAppointment! ? widget.patientShareResponse.clinicID.toString() : "",
        context,
        widget.patientShareResponse.appointmentDate,
        widget.patientShareResponse.appointmentNo,
        widget.patientShareResponse.clinicID,
        widget.patientShareResponse.doctorID,
        paymentMethod[1]);
    // }
  }

  onBrowserLoadStart(String 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'];
      }
    }

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

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

  onBrowserExit(AppoitmentAllHistoryResultList appo, bool isPaymentMade) {
    try {
      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! != null ? tamaraOrderID! : "", num.parse(selectedInstallments!), appo);
        }
      } else {
        checkPaymentStatus(appo);
      }
    } catch (err) {
      print(err);
    }
  }

  checkTamaraPaymentStatus(String orderID, AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getTamaraPaymentStatus(orderID).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res["status"].toString().toLowerCase() == "success") {
        updateTamaraRequestStatus("success", "14", orderID, tamaraOrderID!, int.parse(selectedInstallments!), appo);
      } else {
        updateTamaraRequestStatus(
            "Failed", "00", Utils.getAppointmentTransID(appo.projectID!, appo.clinicID!, appo.appointmentNo!), tamaraOrderID != null ? tamaraOrderID! : "", int.parse(selectedInstallments!), appo);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

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

  updateTamaraRequestStatus(String responseMessage, String status, String clientRequestID, String tamaraOrderID, num selectedInstallments, AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    try {
      DoctorsListService service = new DoctorsListService();
      service.updateTamaraRequestStatus(responseMessage, status, clientRequestID, tamaraOrderID, selectedInstallments).then((res) {
        GifLoaderDialogUtils.hideDialog(context);
        if (tamaraPaymentStatus!.toLowerCase() == "approved") {
          markAppointmentForTamara(appo);
          addAdvancedNumberRequestTamara("Tamara-Advance-0000", tamaraOrderID, appo.appointmentNo.toString(), appo);
        }
      }).catchError((err) {
        print(err);
        AppToast.showErrorToast(message: err);
        GifLoaderDialogUtils.hideDialog(context);
      });
    } catch (err) {
      print(err);
    }
  }

  markAppointmentForTamara(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.markAppointmentForTamara(appo.projectID!, appo.appointmentNo.toString()).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (appo.isLiveCareAppointment!)
        insertLiveCareVIDARequest(appo);
      else
        getAppoQR(context);
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  autoGenerateInvoiceTamara(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.autoGenerateInvoiceTamara(appo.projectID!, appo.appointmentNo.toString(), projectViewModel.user!.mobileNumber!).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (appo.isLiveCareAppointment!)
        insertLiveCareVIDARequest(appo);
      else
        getAppoQR(context);
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    String txn_ref;
    num 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'];
        payment_method = res['PaymentMethod'];
        createAdvancePayment(res, appo);
        projectViewModel.analytics.appointment.payment_success(
            appointment_type: 'regular', payment_method: payment_method, clinic: appo.clinicName, hospital: appo.projectName, txn_amount: "$amount", txn_currency: currency, txn_number: txn_ref);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: res['Response_Message']);
        projectViewModel.analytics.appointment.payment_fail(
            appointment_type: 'regular',
            payment_method: selectedPaymentMethod,
            clinic: appo.clinicName,
            hospital: appo.projectName,
            txn_amount: widget.patientShareResponse.patientShareWithTax.toString(),
            txn_currency: currency,
            error_type: res['Response_Message']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err.toString());
      print(err);
    });
  }

  getApplePayAPQ(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.checkPaymentStatus(Utils.getAppointmentTransID(appo.projectID!, appo.clinicID!, appo.appointmentNo!), false, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);

      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        createAdvancePayment(res, appo);
      } else {
        AppToast.showErrorToast(message: res['Response_Message']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  createAdvancePayment(res, AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    String paymentReference = res['Fort_id'].toString();
    service.createAdvancePayment(appo, appo.projectID.toString(), res['Amount'], res['Fort_id'], res['PaymentMethod'], context).then((res) {
      addAdvancedNumberRequest(
          Utils.isVidaPlusProject(projectViewModel, appo.projectID!)
              ? res['OnlineCheckInAppointments'][0]['AdvanceNumber_VP'].toString()
              : res['OnlineCheckInAppointments'][0]['AdvanceNumber'].toString(),
          paymentReference,
          appo.appointmentNo.toString(),
          appo);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  addAdvancedNumberRequest(String advanceNumber, String paymentReference, String appointmentID, AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    service.addAdvancedNumberRequest(advanceNumber, paymentReference, appointmentID, context).then((res) {
      if (appo.isLiveCareAppointment!) {
        insertLiveCareVIDARequest(appo);
      } else {
        getAppoQR(context);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  Widget _getQRAppo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 30.0, bottom: 40.0),
          alignment: Alignment.center,
          child: Text(TranslationBase.of(context).noNeedToWaitInLine, style: TextStyle(fontSize: 18.0, letterSpacing: 0.8)),
        ),
        Container(
          alignment: Alignment.center,
          child: Image.asset("assets/images/new-design/device_icon.png", width: 120.0, height: 120.0),
        ),
        Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.only(left: 10.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 15.0),
                      child: Row(
                        children: <Widget>[
                          _getBulletPoint("1"),
                          Container(
                            width: MediaQuery.of(context).size.width * 0.8,
                            child: Text(TranslationBase.of(context).useQRAppoAttend, overflow: TextOverflow.fade, style: TextStyle(fontSize: 13.0)),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 15.0),
                      child: Row(
                        children: <Widget>[
                          _getBulletPoint("2"),
                          Container(
                            width: MediaQuery.of(context).size.width * 0.8,
                            child: Text(TranslationBase.of(context).passQRAppoAttend, overflow: TextOverflow.fade, style: TextStyle(fontSize: 13.0)),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 15.0),
                      child: Row(
                        children: <Widget>[
                          _getBulletPoint("3"),
                          Container(
                            width: MediaQuery.of(context).size.width * 0.8,
                            child: Text(TranslationBase.of(context).sitWaitingQR, overflow: TextOverflow.fade, style: TextStyle(fontSize: 13.0)),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
//         Container(
//           alignment: Alignment.bottomCenter,
//           height: MediaQuery.of(context).size.height * 0.18,
//           child: Column(
//             mainAxisAlignment: MainAxisAlignment.end,
//             children: <Widget>[
//               ButtonTheme(
//                 shape: RoundedRectangleBorder(
//                   borderRadius: BorderRadius.circular(10.0),
//                 ),
//                 minWidth: MediaQuery.of(context).size.width * 0.7,
//                 height: 45.0,
//                 child: RaisedButton(
//                   color: new Color(0xFF60686b),
//                   textColor: Colors.white,
//                   disabledTextColor: Colors.white,
//                   disabledColor: new Color(0xFFbcc2c4),
//                   onPressed: () {
// //                    navigateToQR(context);
//                     getAppoQR(context);
//                   },
//                   child: Text(TranslationBase.of(context).viewQR.toUpperCase(),
//                       style: TextStyle(fontSize: 18.0)),
//                 ),
//               ),
//             ],
//           ),
//         ),
      ],
    );
  }

  _getBulletPoint(bulletPoint) {
    return Container(
      margin: EdgeInsets.only(left: 20.0, right: 20.0),
      decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.black),
      width: 20.0,
      height: 20.0,
      child: Center(
        child: Text(bulletPoint,
            style: TextStyle(
              color: Colors.white,
              fontSize: 12.0,
            )),
      ),
    );
  }

  _getHeadingText(text) {
    return Container(
      padding: EdgeInsets.only(bottom: 10.0, left: 20, right: 20),
      child: Text(
        text,
        textAlign: TextAlign.start,
        style: TextStyle(
          fontSize: 16.0,
          letterSpacing: -0.64,
          color: Colors.white,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }

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

  getAppoQR(context) {
    DoctorsListService service = new DoctorsListService();
    service.generateAppointmentQR(widget.patientShareResponse, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      navigateToQR(context, res['AppointmentQR']);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  Future navigateToQR(context, String appoQR) async {
    AppoitmentAllHistoryResultList appointment = new AppoitmentAllHistoryResultList();

    appointment.doctorTitle = "Dr. ";
    appointment.doctorNameObj = widget.patientShareResponse.doctorNameObj;
    appointment.doctorImageURL = widget.patientShareResponse.doctorImageURL;
    appointment.doctorSpeciality = (widget.patientShareResponse.doctorSpeciality != null) ? widget.patientShareResponse.doctorSpeciality as List<String> : [""];
    appointment.projectName = widget.patientShareResponse.projectName;
    appointment.projectID = widget.patientShareResponse.projectID;
    appointment.appointmentDate = widget.patientShareResponse.appointmentDate;
    appointment.isLiveCareAppointment = widget.patientShareResponse.isLiveCareAppointment;
    appointment.startTime = widget.patientShareResponse.startTime;
    appointment.doctorRate = 5;
    appointment.actualDoctorRate = 5;
    appointment.noOfPatientsRate = 0;
    appointment.clinicName = widget.patientShareResponse.clinicName;

    Navigator.push(
        context,
        FadePage(
            page: QRCode(
          patientShareResponse: widget.patientShareResponse,
          appoQR: appoQR,
          appointment: appointment,
        )));
  }

  _getNormalText(text) {
    return Container(
      margin: EdgeInsets.only(top: 5.0, left: 20, right: 20),
      padding: EdgeInsets.only(top: 5.0, bottom: 0),
      child: Text(text,
          textAlign: TextAlign.start,
          style: TextStyle(
            fontSize: 12,
            letterSpacing: -0.36,
            color: Colors.white,
            fontWeight: FontWeight.w600,
          )),
    );
  }

  _getTextStyling() {
    return TextStyle(fontSize: 14.0, color: Colors.white, letterSpacing: 0.7);
  }
}
