import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/viewModels/er/EdOnlineViewModel.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/Authentication/authenticated_user.dart';
import 'package:hmg_patient_app/pages/ToDoList/payment_method_select.dart';
import 'package:hmg_patient_app/pages/base/base_view.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_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/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/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class EdPaymentInformationPage extends StatefulWidget {
  final  HospitalsModel? selectedHospital;

  const EdPaymentInformationPage({Key? key, this.selectedHospital}) : super(key: key);

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

class _EdPaymentInformationPageState extends State<EdPaymentInformationPage> {
  late MyInAppBrowser browser;
  late ProjectViewModel projectViewModel;
  String transID = "";

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return BaseView<EdOnlineViewModel>(
      onModelReady: (model) async => await model.getPatientPaymentInformation(),
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        body: SingleChildScrollView(
          physics: BouncingScrollPhysics(),
          child: Column(
            children: [
              model.erPatientShareModel != null ? Container(
                decoration: cardRadius(12),
                margin: EdgeInsets.fromLTRB(12.0, 30.0, 12.0, 5.0),
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(TranslationBase.of(context).payment,
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 16.0,
                            fontWeight: FontWeight.w600,
                            letterSpacing: -0.64,
                          )),
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.only(top: 10, bottom: 3),
                        child: Row(
                          children: [
                            Expanded(
                              child: _getNormalText(TranslationBase.of(context).patientShareToDo),
                            ),
                            Expanded(
                              child: _getNormalText(model.erPatientShareModel!.patientShare!.toStringAsFixed(2) ?? "0", isBold: true),
                            )
                          ],
                        ),
                      ),
                      mDivider(Colors.grey[200]!),
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.only(top: 3, bottom: 3),
                        child: Row(
                          children: [
                            Expanded(
                              child: _getNormalText(TranslationBase.of(context).patientTaxToDo),
                            ),
                            Expanded(
                              child: _getNormalText(model.erPatientShareModel!.patientTaxAmount!.toStringAsFixed(2) ?? "0", isBold: true),
                            )
                          ],
                        ),
                      ),
                      mDivider(Colors.grey[200]!),
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.only(top: 3, bottom: 3),
                        child: Row(
                          children: [
                            Expanded(
                              child: _getNormalText(TranslationBase.of(context).patientShareTotalToDo),
                            ),
                            Expanded(
                              child: _getNormalText(model.erPatientShareModel!.patientShareWithTax!.toStringAsFixed(2) ?? "0", isBold: true),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ) : Container(),
              mHeight(50.0),
              Text(
                TranslationBase.of(context).payOptions,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 12.0,
                  fontWeight: FontWeight.w600,
                  letterSpacing: -0.46,
                ),
              ),
              Container(margin: EdgeInsets.fromLTRB(20.0, 5.0, 20.0, 5.0), child: getPaymentMethods()),
            ],
          ),
        ),
        bottomSheet: Container(
          color: CustomColors.appBackgroudGreyColor,
          padding: EdgeInsets.all(12.0),
          child: DefaultButton(
            TranslationBase.of(context).payNow.toUpperCase(),
            () {
              Navigator.push(context, FadePage(page: PaymentMethod(
                onSelectedMethod: (String metohd, [String? selectedInstallmentPlan]) {
                  setState(() {});
                }, patientShare: model.erPatientShareModel!.patientShareWithTax!, isFromAdvancePayment: true,
              ))).then(
                (value) {
                  print(value);
                  if (value != null) {
                    AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();
                    appo.projectID = widget.selectedHospital!.iD;
                    openPayment(value[0], projectViewModel.user, model.erPatientShareModel!.patientShareWithTax!, appo);
                  }
                },
              );
            },
            color: CustomColors.green,
            disabledColor: CustomColors.grey2,
          ),
        ),
      ),
    );
  }

  _getNormalText(text, {bool isBold = false}) {
    return Text(
      text,
      style: TextStyle(
        fontSize: isBold ? 12 : 10,
        letterSpacing: -0.5,
        color: isBold ? Colors.black : Colors.grey[700],
        fontWeight: FontWeight.w600,
      ),
    );
  }

  openPayment(String paymentMethod, AuthenticatedUser authenticatedUser, num amount, AppoitmentAllHistoryResultList appo) {
    browser = new MyInAppBrowser(onExitCallback: onBrowserExit, appo: appo, onLoadStartCallback: onBrowserLoadStart);
    transID = Utils.getAdvancePaymentTransID(widget.selectedHospital!.iD, projectViewModel.user!.patientID!);
    browser.openPaymentBrowser(amount, "ER Online Check-In", transID, appo.projectID.toString(), authenticatedUser.emailAddress!, paymentMethod, authenticatedUser.patientType,
        authenticatedUser.firstName!, authenticatedUser.patientID, authenticatedUser, browser, false, "3", "", context);
  }

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

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    service.checkPaymentStatus(transID, false, AppGlobal.context).then((res) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      String paymentInfo = res['Response_Message'];
      if (paymentInfo == 'Success') {
        ER_createAdvancePayment(res, appo);
      } else {
        AppToast.showErrorToast(message: res['Response_Message']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  ER_createAdvancePayment(payment_res, AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    service.ER_createAdvancePayment(appo, appo.projectID.toString(), payment_res['Amount'], payment_res['Fort_id'], payment_res['PaymentMethod'], AppGlobal.context).then((res) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      ER_InsertEROnlinePaymentDetails(payment_res, appo);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  ER_InsertEROnlinePaymentDetails(payment_res, AppoitmentAllHistoryResultList appo) {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(AppGlobal.context);
    service.ER_InsertEROnlinePaymentDetails(appo, appo.projectID.toString(), payment_res['Amount'], payment_res['Fort_id'], payment_res['PaymentMethod'], AppGlobal.context).then((res) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showSuccessToast(message: TranslationBase.of(context).success);
      Navigator.of(context).pop();
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(AppGlobal.context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }
}
