import 'dart:io';

import 'package:hmg_patient_app/config/config.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/Appointments/PatientShareResposne.dart';
import 'package:hmg_patient_app/models/Authentication/authenticated_user.dart';
import 'package:hmg_patient_app/pages/BookAppointment/QRCode.dart';
import 'package:hmg_patient_app/pages/ToDoList/payment_method_select.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/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/dragable_sheet.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/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class CovidPaymentSummary extends StatefulWidget {
  PatientShareResponse? patientShareResponse;
  String selectedPaymentMethod;
  String? selectedInstallmentPlan;
  MyInAppBrowser? browser;
  AuthenticatedUser? authenticatedUser;
  AppSharedPreferences sharedPref = AppSharedPreferences();

  CovidPaymentSummary({required this.patientShareResponse, required this.selectedPaymentMethod});

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

class _CovidPaymentSummaryState extends State<CovidPaymentSummary> {
  late ProjectViewModel projectViewModel;
  late String tamaraPaymentStatus;
  late String tamaraOrderID;

  String transID = "";

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).covidTest,
      isShowAppBar: true,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      backgroundColor: CustomColors.appBackgroudGrey2Color,
      body: SingleChildScrollView(
        physics: ScrollPhysics(),
        child: Container(
          margin: EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                TranslationBase.of(context).confirmThePayment,
                style: TextStyle(
                  fontSize: 19,
                  fontWeight: FontWeight.bold,
                  letterSpacing: -1.46,
                ),
              ),
              SizedBox(
                height: 12,
              ),
              Row(
                children: [
                  Text(
                    TranslationBase.of(context).totalBalance + ": ",
                    style: TextStyle(
                      fontSize: 12,
                      letterSpacing: -0.60,
                    ),
                  ),
                  Text(
                    '${widget.patientShareResponse!.patientShareWithTax} ' + TranslationBase.of(context).sar,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      letterSpacing: -0.60,
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 12,
              ),
              Row(
                children: [
                  Container(
                    width: 20,
                    height: 20,
                    decoration: containerColorRadiusBorderWidth(CustomColors.accentColor, 200, Colors.white, 4),
                  ),
                  Container(
                    height: 100.0,
                    padding: EdgeInsets.all(7.0),
                    child: Image.asset(getImagePath(widget.selectedPaymentMethod!), width: 100, height: 100),
                  ),
                  mFlex(1),
                  InkWell(
                    onTap: () {
                      showDraggableDialog(
                          context,
                          PaymentMethod(
                            onSelectedMethod: (String metohd, [String? selectedInstallmentPlan]) {
                              widget.selectedPaymentMethod = metohd;
                              widget.selectedInstallmentPlan = selectedInstallmentPlan;
                              setState(() {});
                            },
                            patientShare: widget.patientShareResponse!.patientShareWithTax,
                          ));
                    },
                    child: Text(
                      TranslationBase.of(context).changePayment,
                      style: TextStyle(fontWeight: FontWeight.w600, fontSize: 12, letterSpacing: -0.48, decoration: TextDecoration.underline, color: CustomColors.accentColor),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 12,
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: showDetail(
                      TranslationBase.of(context).fileNumber,
                      projectViewModel.user!.patientID.toString(),
                    ),
                  ),
                  mWidth(6),
                  Expanded(
                    flex: 1,
                    child: showDetail(
                      TranslationBase.of(context).name,
                      projectViewModel.user!.firstName.toString(),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 6,
              ),
              showDetail(TranslationBase.of(context).mobileNumber, projectViewModel.user!.mobileNumber!),
              SizedBox(
                height: 6,
              ),
              showDetail(
                TranslationBase.of(context).depositorName,
                projectViewModel.user!.firstName! + " " + projectViewModel.user!.middleName! + " " + projectViewModel.user!.lastName!,
              )
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        margin: EdgeInsets.only(bottom: 5.0),
        width: double.infinity,
        padding: EdgeInsets.all(12),
        child: DefaultButton(
          TranslationBase.of(context).confirm.toUpperCase(),
          () {
            startPaymentProcess(projectViewModel.user!);
          },
          color: CustomColors.green,
        ),
      ),
    );
  }

  Widget showDetail(String title, String value) {
    return Container(
      width: double.infinity,
      child: Container(
        decoration: cardRadius(12),
        margin: EdgeInsets.zero,
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                title,
                style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, letterSpacing: -0.64),
              ),
              Text(
                value,
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600, letterSpacing: -0.64, color: Colors.grey),
              ),
            ],
          ),
        ),
      ),
    );
  }

  startPaymentProcess(AuthenticatedUser authenticatedUser) {
    AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
    appo.projectID = widget.patientShareResponse!.projectID;
    appo.clinicID = widget.patientShareResponse!.clinicID;
    appo.appointmentNo = widget.patientShareResponse!.appointmentNo;

    openPayment(widget.selectedPaymentMethod, authenticatedUser, double.parse(widget.patientShareResponse!.patientShareWithTax.toString()), widget.patientShareResponse!, appo);
  }

  openPayment(String paymentMethod, AuthenticatedUser authenticatedUser, num amount, PatientShareResponse patientShareResponse, AppoitmentAllHistoryResultList appo) async {
    widget.browser = new MyInAppBrowser(onExitCallback: onBrowserExit, appo: appo, onLoadStartCallback: onBrowserLoadStart, context: context);
    transID = Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo);
    widget.browser!.openPaymentBrowser(
        amount,
        "Covid appointment payment",
        Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo),
        appo.projectID.toString(),
        authenticatedUser.emailAddress!,
        paymentMethod,
        authenticatedUser.patientType,
        authenticatedUser.firstName!,
        authenticatedUser.patientID,
        authenticatedUser,
        widget.browser!,
        widget.patientShareResponse!.isLiveCareAppointment!,
        "2",
        "",
        widget.patientShareResponse!.appointmentDate,
        widget.patientShareResponse!.appointmentNo,
        widget.patientShareResponse!.clinicID,
        widget.patientShareResponse!.doctorID,
        widget.selectedInstallmentPlan);
  }

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

    if (widget.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) {
    print("onBrowserExit Called!!!!");
    try {
      if (widget.selectedPaymentMethod == "TAMARA") {
        // checkTamaraPaymentStatus(Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), appo);
        checkTamaraPaymentStatus(transID, appo);
        // if (tamaraPaymentStatus != null && tamaraPaymentStatus.toLowerCase() == "approved") {
        //   updateTamaraRequestStatus("success", "14", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID, num.parse(widget.selectedInstallmentPlan), appo);
        // } else {
        //   updateTamaraRequestStatus("Failed", "00", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID != null ? tamaraOrderID : "",
        //       num.parse(widget.selectedInstallmentPlan), 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(widget.selectedInstallmentPlan!), appo);
      } else {
        updateTamaraRequestStatus("Failed", "00", transID, tamaraOrderID != null ? tamaraOrderID : "",
            num.parse(widget.selectedInstallmentPlan!), 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);
      getAppoQR(context);
      // autoGenerateInvoiceTamara(appo);
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  autoGenerateInvoiceTamara(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    var apptData = {
      "AppointmentNo": appo.appointmentNo.toString(),
      "DoctorID": appo.doctorID.toString(),
      "ServiceID": appo.serviceID.toString(),
      "ProjectID": appo.projectID.toString(),
      "ClinicID": appo.clinicID.toString(),
      "AppointmentDate": appo.appointmentDate.toString(),
    };
    DoctorsListService service = new DoctorsListService();
    service.autoGenerateInvoiceTamara(appo.projectID!, appo.appointmentNo.toString(), projectViewModel.user!.mobileNumber!).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      getAppoQR(context);
    }).catchError((err) {
      print(err);
      AppToast.showErrorToast(message: err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.checkPaymentStatus(transID, false, context).then((res) {
      print("Printing Payment Status Reponse!!!!");
      print(res);
      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        createAdvancePayment(res, appo);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: res['Response_Message']);
        Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(builder: (context) => LandingPage()),
          (Route<dynamic> route) => false,
        );
      }
    }).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());
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

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

  getAppoQR(context) {
    DoctorsListService service = new DoctorsListService();
    service.generateAppointmentQR(widget.patientShareResponse!, context).then((res) {
      print(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 {
    Navigator.push(
        context,
        FadePage(
            page: QRCode(
          patientShareResponse: widget.patientShareResponse,
          appoQR: appoQR,
        )));
  }

  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;
      case "TAMARA":
        return 'assets/images/new/payment/tamara.png';
        break;
    }

    return 'assets/images/new/payment/Mada.png';
  }
}
