import 'package:hmg_patient_app/core/enum/viewstate.dart';
import 'package:hmg_patient_app/core/model/pharmacies/order_detail.dart';
import 'package:hmg_patient_app/core/viewModels/pharmacyModule/OrderPreviewViewModel.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/locator.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/landing/landing_page_pharmcy.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/navigation_service.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/buttons/custom_text_button.dart';
import 'package:hmg_patient_app/widgets/data_display/text.dart';
import 'package:hmg_patient_app/widgets/in_app_browser/InAppBrowser.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class PaymentBottomWidget extends StatelessWidget {
  final OrderPreviewViewModel? model;
  static bool isChecked = true;

  BuildContext? context;
  MyInAppBrowser? browser;

  PaymentBottomWidget(this.model);

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    this.context = context;
    OrderPreviewViewModel orderPreviewViewModel = Provider.of(context);
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
      child: orderPreviewViewModel!.paymentCheckoutData!.cartDataVisible!
          ? Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Container(
                        margin: EdgeInsets.symmetric(horizontal: 0, vertical: 4),
                        child: Row(
                          children: [
                            isChecked
                                ? Texts(
                                    "${TranslationBase.of(context).sar} ${model!.cartResponse.totalAmount}",
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                    color: Color(0xff929295),
                                  )
                                : Texts(
                                    "${TranslationBase.of(context).sar} ${(model!.cartResponse.totalAmount)!.toStringAsFixed(2)}",
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                    color: Color(0xff929295),
                                  ),
                            Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 4),
                              child: Texts(
                                "${TranslationBase.of(context).inclusiveVat}",
                                fontSize: 8,
                                color: Color(0xff929295),
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Texts(
                        "${model!.cartResponse.quantityCount} ${TranslationBase.of(context).items}",
                        fontSize: 10,
                        color: Colors.grey,
                        fontWeight: FontWeight.bold,
                      ),
                    ],
                  ),
                  Container(
                    child: CustomTextButton(
                        elevation: 0,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                          side: BorderSide(
                            color: Color(0xff929295),
                            width: 1,
                          ),
                        ),
                        disabledForegroundColor: (orderPreviewViewModel.paymentCheckoutData.address != null && orderPreviewViewModel.paymentCheckoutData.paymentOption != null)
                            ? Colors.green
                            : Color(0xff929295).withOpacity(0.38),
                        disabledBackgroundColor: (orderPreviewViewModel.paymentCheckoutData.address != null && orderPreviewViewModel.paymentCheckoutData.paymentOption != null)
                            ? Colors.green
                            : Color(0xff929295).withOpacity(0.12),
                        backgroundColor:
                            (orderPreviewViewModel.paymentCheckoutData.address != null && orderPreviewViewModel.paymentCheckoutData.paymentOption != null) ? Colors.green : Color(0xff929295),
                      onPressed: (orderPreviewViewModel.paymentCheckoutData.address != null && orderPreviewViewModel.paymentCheckoutData.paymentOption != null)
                          ? () async {
                              GifLoaderDialogUtils.showMyDialog(context);
                              await model!.makeOrder(projectViewModel.havePrivilege(83));
                              if (model!.state == ViewState.Idle) {
                                AppToast.showSuccessToast(message: TranslationBase.of(context).compeleteOrderMsg);
                                GifLoaderDialogUtils.hideDialog(context);
                                openPayment(model!.orderListModel[0], model!.authenticatedUserObject.user!);
                              } else {
                                AppToast.showErrorToast(message: model!.error);
                              }
                              navigateToCartPage();
                              // Navigator.pop(context);
                              // Navigator.pop(context);
                              // Navigator.pop(context);
                              // Navigator.pop(context);
                            }
                          : null,
                      child: Padding(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        child: new Text(
                          "${TranslationBase.of(context).proceedPay}",
                          style: new TextStyle(
                              color:
                                  (orderPreviewViewModel.paymentCheckoutData.address != null && orderPreviewViewModel.paymentCheckoutData.paymentOption != null) ? Colors.white : Colors.grey.shade400,
                              fontWeight: FontWeight.bold,
                              fontSize: 12),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            )
          : Container(),
    );
  }

  openPayment(
    OrderDetailModel order,
    AuthenticatedUser authenticatedUser,
  ) {
    browser = new MyInAppBrowser(onExitCallback: onBrowserExit, onLoadStartCallback: onBrowserLoadStart);

    browser!.openPharmacyPaymentBrowser!(order, order.orderTotal, 'ePharmacy Order', order.id!, order!.billingAddress!.email!, order.customValuesXml!,
        "${authenticatedUser.firstName} ${authenticatedUser.middleName} ${authenticatedUser.lastName}", authenticatedUser.patientID, authenticatedUser, browser!);
  }

  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;
      }
    });
  }

  navigateToCartPage() {
    Navigator.pushAndRemoveUntil(locator<NavigationService>().navigatorKey.currentContext!, MaterialPageRoute(builder: (context) => LandingPagePharmacy(currentTab: 0)), (Route<dynamic> r) => false);
  }

  onBrowserExit(AppoitmentAllHistoryResultList appo, bool isPaymentMade) {
    print("onBrowserExit Called!!!!");
    AppToast.showSuccessToast(message: "شكراً\nPayment status for your order is Paid");
    // Navigator.pop(context);
    // Navigator.pop(context);
    // } else {
    //   AppToast.showErrorToast(message: "Transaction Failed!\Your transaction is field to some reason please try again or contact to the administration");
    //   // Navigator.pop(context);
    //   // Navigator.pop(context);
    // }
  }
}
