import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/PatientShareResposne.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/pages/Blood/new_text_Field.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/QRCode.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:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class CovidPaymentSummary extends StatefulWidget {
  PatientShareResponse patientShareResponse;

  final String selectedPaymentMethod;
  MyInAppBrowser browser;
  AuthenticatedUser authenticatedUser;
  AppSharedPreferences sharedPref = AppSharedPreferences();
  String transID = "";

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

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

class _CovidPaymentSummaryState extends State<CovidPaymentSummary> {
  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).covidTest,
      isShowAppBar: true,
      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:
                        Image.asset(getImagePath(widget.selectedPaymentMethod)),
                  ),
                  Texts(
                    '${widget.patientShareResponse.patientShareWithTax} ' +
                        TranslationBase.of(context).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:
                            projectViewModel.user.patientID.toString(),
                        isEnabled: false,
                      ),
                    ),
                  ),
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.all(3),
                      child: NewTextFields(
                        hintText: TranslationBase.of(context).name,
                        initialValue: projectViewModel.user.firstName,
                        isEnabled: false,
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 12,
              ),
              NewTextFields(
                hintText: TranslationBase.of(context).mobileNumber,
                initialValue: projectViewModel.user.mobileNumber,
                isEnabled: false,
              ),
              SizedBox(
                height: 12,
              ),
              NewTextFields(
                hintText: TranslationBase.of(context).depositorName,
                initialValue: projectViewModel.user.firstName +
                    " " +
                    projectViewModel.user.middleName +
                    " " +
                    projectViewModel.user.lastName,
                isEnabled: false,
              ),
            ],
          ),
        ),
      ),
      bottomSheet: Container(
        height: MediaQuery.of(context).size.height * 0.1,
        width: double.infinity,
        padding: EdgeInsets.all(12),
        child: SecondaryButton(
          textColor: Colors.white,
          color: Theme.of(context).primaryColor,
          label: TranslationBase.of(context).confirm.toUpperCase(),
          onTap: () {
            startPaymentProcess(projectViewModel.user);
          },
        ),
      ),
    );
  }

  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,
      double amount,
      PatientShareResponse patientShareResponse,
      AppoitmentAllHistoryResultList appo) async {
    if (paymentMethod == "ApplePay") {
      // await widget.chromeBrowser.open(
      //     url: "https://applepay-datatrans-sample.herokuapp.com/",
      //     options: ChromeSafariBrowserClassOptions(
      //         android: AndroidChromeCustomTabsOptions(
      //             addDefaultShareMenuItem: false),
      //         ios: IOSSafariOptions(barCollapsingEnabled: true)));
    } else {
      widget.browser = new MyInAppBrowser(
          onExitCallback: onBrowserExit,
          appo: appo,
          onLoadStartCallback: onBrowserLoadStart);

      widget.browser.openPaymentBrowser(
          amount,
          "Appointment check in",
          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,
          null,
          null,
          widget.patientShareResponse.appointmentDate,
          widget.patientShareResponse.appointmentNo,
          widget.patientShareResponse.clinicID,
          widget.patientShareResponse.doctorID);
    }
  }

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

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

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service
        .checkPaymentStatus(
            Utils.getAppointmentTransID(
                appo.projectID, appo.clinicID, appo.appointmentNo),
            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']);
      }
    }).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) {
      print(res['OnlineCheckInAppointments'][0]['AdvanceNumber']);
      addAdvancedNumberRequest(
          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) {
      print(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-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;
    }

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