import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/InPatientServices/get_inpatient_advance_requests_response_model.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.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_new.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/in_app_browser/InAppBrowser.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';

class InPatientPendingAdvancePayment extends StatefulWidget {
  InPatientAdvanceResponseModel inPatientAdvanceResponseModel;
  bool isHasData;

  InPatientPendingAdvancePayment({required this.isHasData, required this.inPatientAdvanceResponseModel});

  @override
  State<InPatientPendingAdvancePayment> createState() => _InPatientPendingAdvancePaymentState();
}

class _InPatientPendingAdvancePaymentState extends State<InPatientPendingAdvancePayment> {
  late ProjectViewModel projectViewModel;
  InAppBrowser browser = new InAppBrowser();

  var _InAppBrowserOptions = InAppBrowserClassOptions(
      inAppWebViewGroupOptions: InAppWebViewGroupOptions(
          crossPlatform: InAppWebViewOptions(useShouldOverrideUrlLoading: true, transparentBackground: false),
          ios: IOSInAppWebViewOptions(applePayAPIEnabled: true, isFraudulentWebsiteWarningEnabled: false)),
      crossPlatform: InAppBrowserOptions(hideUrlBar: true, toolbarTopBackgroundColor: Colors.white),
      android: AndroidInAppBrowserOptions(),
      ios:
          IOSInAppBrowserOptions(hideToolbarBottom: true, toolbarBottomBackgroundColor: Colors.white, closeButtonColor: Colors.white, presentationStyle: IOSUIModalPresentationStyle.OVER_FULL_SCREEN));

  @override
  void initState() {
    // browser = new InAppBrowser(onLoadStartCallback: onBrowserLoadStart);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: double.infinity,
            child: Container(
              decoration: cardRadius(12),
              margin: EdgeInsets.zero,
              child: Padding(
                padding: const EdgeInsets.all(12.0),
                child: widget.isHasData && widget.inPatientAdvanceResponseModel!.responseInpatientAdvanceInfo != null
                    ? Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "Payment request for: ",
                            // TranslationBase.of(context).covidBookAppo,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                              letterSpacing: -0.64,
                            ),
                          ),
                          mHeight(6),
                          Row(
                            children: [
                              Text(
                                TranslationBase.of(context).patientName + ":",
                                style: TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 10,
                                  letterSpacing: -0.6,
                                  color: CustomColors.grey,
                                ),
                              ),
                              mWidth(3),
                              Text(
                                projectViewModel.user.firstName! + " " + projectViewModel.user.lastName!,
                                style: TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 12,
                                  letterSpacing: -0.48,
                                ),
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              Text(
                                TranslationBase.of(context).identificationNumber + ":",
                                style: TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 10,
                                  letterSpacing: -0.6,
                                  color: CustomColors.grey,
                                ),
                              ),
                              mWidth(3),
                              Text(
                                projectViewModel.user.patientIdentificationNo!,
                                style: TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 12,
                                  letterSpacing: -0.48,
                                ),
                              ),
                            ],
                          ),
                          Row(
                            children: [
                              Text(
                                TranslationBase.of(context).mrn + ":",
                                style: TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 10,
                                  letterSpacing: -0.6,
                                  color: CustomColors.grey,
                                ),
                              ),
                              mWidth(3),
                              Text(
                                projectViewModel.user.patientID.toString(),
                                style: TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 12,
                                  letterSpacing: -0.48,
                                ),
                              ),
                            ],
                          ),
                        ],
                      )
                    : getNoDataWidget(context),
              ),
            ),
          ),
          mHeight(12),
          // Expanded(child: Container()),
          widget.isHasData
              ? Container(
                  decoration: cardRadius(12.0),
                  margin: EdgeInsets.zero,
                  padding: EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            TranslationBase.of(context).patientShareTotalToDo,
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                              letterSpacing: -0.64,
                            ),
                          ),
                          Row(
                            children: [
                              SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 16, height: 16),
                              mWidth(6),
                              Text(
                                "${widget.inPatientAdvanceResponseModel.responseInpatientAdvanceInfo![0].requestedAmount}",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 24,
                                  letterSpacing: -0.64,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      SizedBox(height: 12),
                      Text(
                        TranslationBase.of(context).YouCanPayByTheFollowingOptions,
                        style: TextStyle(
                          fontSize: 14.0,
                          fontWeight: FontWeight.w600,
                          color: Color(0xff2B353E),
                          letterSpacing: -0.64,
                        ),
                      ),
                      SizedBox(height: 12),
                      SizedBox(
                        width: MediaQuery.of(context).size.width * 0.75,
                        child: getPaymentMethods(),
                      ),
                      SizedBox(height: 12),
                      DefaultButton(
                        TranslationBase.of(context).payNow.toUpperCase(),
                        () {
                          getInPatientPaymentLink(false);
                        },
                        // : null,
                        color: CustomColors.green,
                        disabledColor: CustomColors.grey2,
                      ),
                      SizedBox(height: 12),
                      Text(
                        TranslationBase.of(context).copyLinkTxt,
                        style: TextStyle(
                          fontSize: 14.0,
                          fontWeight: FontWeight.w600,
                          color: Color(0xff2B353E),
                          letterSpacing: -0.64,
                        ),
                      ),
                      SizedBox(height: 12),
                      DefaultButton(
                        TranslationBase.of(context).copyLink.toUpperCase(),
                        () {
                          getInPatientPaymentLink(true);
                        },
                        svgIcon: "assets/images/new/copy.svg",
                        color: CustomColors.accentColor,
                        disabledColor: CustomColors.grey2,
                      ),
                    ],
                  ),
                )
              : Container(),
        ],
      ),
    );
  }

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

  void getInPatientPaymentLink(bool isCopy) {
    ClinicListService service = new ClinicListService();
    GifLoaderDialogUtils.showMyDialog(context);
    int orderID = int.parse(DateTime.now().microsecondsSinceEpoch.toString().substring(7, 15));
    int clinicID = projectViewModel.isPatientAdmitted ? projectViewModel.getAdmissionInfoResponseModel.clinicID! : 17;
    service
        .getInPatientPaymentLink(
      widget.inPatientAdvanceResponseModel.responseInpatientAdvanceInfo![0].paymentRequestID!,
      projectViewModel.inPatientProjectID,
      // projectViewModel.getAdmissionInfoResponseModel.admissionNo!,
      projectViewModel.isPatientAdmitted ? projectViewModel.getAdmissionInfoResponseModel.admissionRequestNo! : projectViewModel.getAdmissionRequestInfoResponseModel.admissionRequestNo!,
      orderID,
      projectViewModel.user.firstName! + " " + projectViewModel.user.lastName!,
      projectViewModel.user.emailAddress!,
      widget.inPatientAdvanceResponseModel.responseInpatientAdvanceInfo![0].requestedAmount!,
      projectViewModel.user.patientIdentificationNo!,
      clinicID,
      widget.inPatientAdvanceResponseModel.responseInpatientAdvanceInfo![0].paymentRequestID!,
    )
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res["MessageStatus"] == 1) {
        String paymentLink = res["PaymentUrl"];
        print(paymentLink);
        if (isCopy) {
          Share.share(paymentLink);
        } else {
          Uri uri = Uri.parse(paymentLink);
          launchUrl(uri, mode: LaunchMode.externalApplication);
          // this.browser.openUrlRequest(urlRequest: URLRequest(url: WebUri.uri(Uri.parse(paymentLink))), options: _InAppBrowserOptions);
        }
      } else {
        AppToast.showErrorToast(message: res["endUserMessage"]);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }
}
