import 'dart:io';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:hmg_patient_app/config/size_config.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/LiveCare/ERAppointmentFeesResponse.dart';
import 'package:hmg_patient_app/pages/insurance/insurance_update_screen.dart';
import 'package:hmg_patient_app/pages/landing/landing_page.dart';
import 'package:hmg_patient_app/pages/livecare/live_care_user_agreement_page.dart';
import 'package:hmg_patient_app/services/livecare_services/livecare_provider.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/PlatformBridge.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/location_util.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/dialogs/confirm_dialog.dart';
import 'package:hmg_patient_app/widgets/dialogs/covid_consent_dialog.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:flutter_svg/flutter_svg.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class LiveCarePatmentPage extends StatefulWidget {
  GetERAppointmentFeesList getERAppointmentFeesList;
  int waitingTime;
  String clinicName;
  bool isPharmaLiveCare;
  String pharmaLiveCareClientID;
  int selectedCallType;

  LiveCarePatmentPage(
      {required this.getERAppointmentFeesList, required this.waitingTime, required this.clinicName, this.isPharmaLiveCare = false, this.pharmaLiveCareClientID = "", required this.selectedCallType});

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

class _LiveCarePatmentPageState extends State<LiveCarePatmentPage> {
  int _selected = 0;

  late ProjectViewModel projectViewModel;
  late LocationUtils locationUtils;

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    final double itemHeight = ((size.height - kToolbarHeight - 24) * 0.42) / 2;
    final double itemWidth = size.width / 2;
    projectViewModel = Provider.of(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).livecare,
      isShowAppBar: true,
      showNewAppBarTitle: true,
      showNewAppBar: true,
      description: TranslationBase.of(context).erConsultation,
      onTap: () {
        //Navigator.pop(context);
        Navigator.pop(context);
      },
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: [
            Expanded(
              child: Padding(
                padding: EdgeInsets.all(21),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    Text(
                      widget.clinicName,
                      style: TextStyle(
                        fontSize: 19.0,
                        fontWeight: FontWeight.bold,
                        letterSpacing: -1.44,
                      ),
                    ),
                    mHeight(8),
                    Text(
                      TranslationBase.of(context).expectedWaiting,
                      textAlign: TextAlign.end,
                      style: TextStyle(
                        fontSize: 14.0,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.56,
                        color: CustomColors.textColor,
                      ),
                    ),
                    Text(
                      widget.waitingTime.toString() + " " + TranslationBase.of(context).minute,
                      textAlign: TextAlign.start,
                      style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                        color: CustomColors.accentColor,
                        letterSpacing: -0.66,
                      ),
                    ),
                    mHeight(16),
                    Container(
                      decoration: cardRadius(12),
                      padding: EdgeInsets.all(12),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            TranslationBase.of(context).erConsultFee,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 16.0,
                              fontWeight: FontWeight.w600,
                              letterSpacing: -0.64,
                            ),
                          ),
                          mHeight(10),
                          Row(
                            children: [
                              Expanded(
                                child: Text(
                                  TranslationBase.of(context).patientShareToDo,
                                  style: TextStyle(
                                    fontSize: 10,
                                    letterSpacing: -0.4,
                                    color: CustomColors.textColor,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: (widget.getERAppointmentFeesList.currency! == "ريال" || widget.getERAppointmentFeesList.currency! == "SAR")
                                    ? Row(
                                        children: [
                                          projectViewModel.isArabic ? Container() : SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 16, height: 16),
                                          mWidth(6),
                                          Text(
                                            widget.getERAppointmentFeesList.amount!,
                                            style: TextStyle(
                                              fontSize: 12,
                                              letterSpacing: -0.48,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                          mWidth(6),
                                          projectViewModel.isArabic ? SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 16, height: 16) : Container(),
                                        ],
                                      )
                                    : Text(
                                        widget.getERAppointmentFeesList.amount! + " " + widget.getERAppointmentFeesList.currency!,
                                        style: TextStyle(
                                          fontSize: 12,
                                          letterSpacing: -0.48,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                              ),
                            ],
                          ),
                          mHeight(4),
                          mDivider(CustomColors.lightGreyColor),
                          mHeight(4),
                          Row(
                            children: [
                              Expanded(
                                child: Text(
                                  TranslationBase.of(context).patientTaxToDo,
                                  style: TextStyle(
                                    fontSize: 10,
                                    letterSpacing: -0.4,
                                    color: CustomColors.textColor,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: (widget.getERAppointmentFeesList.currency! == "ريال" || widget.getERAppointmentFeesList.currency! == "SAR")
                                    ? Row(
                                        children: [
                                          projectViewModel.isArabic ? Container() : SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 16, height: 16),
                                          mWidth(6),
                                          Text(
                                            widget.getERAppointmentFeesList.tax!,
                                            style: TextStyle(
                                              fontSize: 12,
                                              letterSpacing: -0.48,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                          mWidth(6),
                                          projectViewModel.isArabic ? SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 16, height: 16) : Container(),
                                        ],
                                      )
                                    : Text(
                                        widget.getERAppointmentFeesList.tax! + " " + widget.getERAppointmentFeesList.currency!,
                                        style: TextStyle(
                                          fontSize: 12,
                                          letterSpacing: -0.48,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                              ),
                            ],
                          ),
                          mHeight(4),
                          mDivider(CustomColors.lightGreyColor),
                          mHeight(4),
                          Row(
                            children: [
                              Expanded(
                                child: Text(
                                  TranslationBase.of(context).patientShareTotalToDo,
                                  style: TextStyle(
                                    fontSize: 10,
                                    letterSpacing: -0.4,
                                    color: CustomColors.textColor,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                              ),
                              Expanded(
                                child: (widget.getERAppointmentFeesList.currency! == "ريال" || widget.getERAppointmentFeesList.currency! == "SAR")
                                    ? Row(
                                        children: [
                                          projectViewModel.isArabic ? Container() : SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 16, height: 16),
                                          mWidth(6),
                                          Text(
                                            widget.getERAppointmentFeesList.total!,
                                            style: TextStyle(
                                              fontSize: 12,
                                              letterSpacing: -0.48,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                          mWidth(6),
                                          projectViewModel.isArabic ? SvgPicture.asset("assets/images/new/Saudi_Riyal_Symbol.svg", width: 16, height: 16) : Container(),
                                        ],
                                      )
                                    : Text(
                                        widget.getERAppointmentFeesList.total! + " " + widget.getERAppointmentFeesList.currency!,
                                        style: TextStyle(
                                          fontSize: 12,
                                          letterSpacing: -0.48,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    mHeight(12),
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: cardRadius(12),
                      child: Row(
                        children: <Widget>[
                          SvgPicture.asset(
                            "assets/images/new/services/raise_comp.svg",
                            color: CustomColors.green,
                            width: 18,
                            height: 18,
                          ),
                          mWidth(10),
                          Expanded(
                            child: Text(
                              TranslationBase.of(context).insuredPatient,
                              style: TextStyle(
                                fontSize: 10.0,
                                letterSpacing: -0.4,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    // mHeight(0.0),
                    Container(
                      margin: EdgeInsets.only(top: 16.0),
                      child: Row(
                        children: <Widget>[
                          Radio(
                            value: 1,
                            groupValue: _selected,
                            onChanged: (val) {
                              onRadioChanged(val!);
                            },
                          ),
                          Text(
                            TranslationBase.of(context).agreeTo,
                            style: new TextStyle(
                              fontSize: 12.0,
                              fontWeight: FontWeight.w600,
                              letterSpacing: -0.48,
                              color: CustomColors.textColor,
                            ),
                          ),
                          mWidth(4),
                          InkWell(
                            onTap: () {
                              Navigator.of(context).push(FadePage(page: LiveCareUserAgreementPage()));
                              // launchUrl(Uri.parse(
                              //   "https://hmg.com/en/Pages/Privacy.aspx",
                              // ));
                            },
                            child: Text(
                              TranslationBase.of(context).termsConditoins,
                              style: new TextStyle(
                                fontSize: 12.0,
                                fontWeight: FontWeight.w600,
                                letterSpacing: -0.48,
                                color: CustomColors.accentColor,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    AutoSizeText(
                      TranslationBase.of(context).selectedCallType,
                      maxLines: 1,
                      minFontSize: 12,
                      style: TextStyle(
                        fontSize: SizeConfig.textMultiplier! * 2.0,
                        fontWeight: FontWeight.w600,
                        letterSpacing: -0.39,
                        height: 0.8,
                      ),
                    ),
                    mHeight(12.0),
                    Row(
                      children: <Widget>[
                        SvgPicture.asset(
                          getCallTypeImagePath(),
                          width: 18,
                          height: 18,
                        ),
                        mWidth(10),
                        Text(
                          getCallTypeText(),
                          style: TextStyle(
                            fontSize: 14.0,
                            letterSpacing: -0.4,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                    mFlex(1),
                    Text(
                      TranslationBase.of(context).upComingPayOption,
                      style: new TextStyle(
                        fontSize: 12.0,
                        letterSpacing: -0.36,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
                      child: getPaymentMethods(),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.all(12),
              color: Colors.white,
              child: Column(
                children: [
                  Flex(
                    direction: Axis.horizontal,
                    children: <Widget>[
                      Expanded(
                        child: DefaultButton(
                          TranslationBase.of(context).cancel,
                          () {
                            if (widget.isPharmaLiveCare) cancelAPI();
                            Navigator.pop(context, false);
                          },
                        ),
                      ),
                      mWidth(12),
                      Expanded(
                        child: DefaultButton(
                          TranslationBase.of(context).next,
                          () {
                            if (_selected == 0) {
                              AppToast.showErrorToast(message: TranslationBase.of(context).pleaseAcceptTerms);
                            } else {
                              if (widget.isPharmaLiveCare) {
                                Navigator.pop(context, true);
                              } else {
                                askVideoCallPermission().then((value) async {
                                  if (value == true) {
                                    locationUtils = new LocationUtils(isShowConfirmDialog: false, context: context);
                                    locationUtils.getCurrentLocation(callBack: (value) {
                                      print(value);
                                    });
                                    if (Platform.isAndroid && !(await PlatformBridge.shared().isDrawOverAppsPermissionAllowed())) {
                                      await drawOverAppsMessageDialog(context).then((value) {
                                        return false;
                                      });
                                    } else {
                                      Navigator.pop(context, true);
                                      projectViewModel.analytics.liveCare.livecare_immediate_consultation_TnC(clinic: widget.clinicName);
                                    }
                                  } else {
                                    openPermissionsDialog();
                                  }
                                });
                              }
                            }
                          },
                          color: CustomColors.green,
                        ),
                      ),
                    ],
                  ),
                  widget.getERAppointmentFeesList.isCash!
                      ? Column(
                          children: [
                            mHeight(10.0),
                            Text(
                              TranslationBase.of(context).cashAmountUpdateInsurance,
                              style: TextStyle(
                                fontSize: 14.0,
                                fontWeight: FontWeight.w600,
                                color: Color(0xff2E303A),
                              ),
                            ),
                            mHeight(5.0),
                            DefaultButton(
                              TranslationBase.of(context).updateInsuranceText,
                              () {
                                Navigator.pop(context, null);
                                Navigator.pushAndRemoveUntil(
                                  context,
                                  MaterialPageRoute(builder: (context) => LandingPage()),
                                  (Route<dynamic> route) => false,
                                ).then((value) {
                                  Navigator.push(context, FadePage(page: InsuranceUpdate()));
                                });
                              },
                              color: Color(0xffEAA118),
                              textColor: Colors.white,
                            ),
                          ],
                        )
                      : Container(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  String getCallTypeImagePath() {
    String callTypeImagePath = "";
    switch (widget.selectedCallType) {
      case 1:
        callTypeImagePath = "assets/images/new/services/video_call.svg";
        break;
      case 2:
        callTypeImagePath = "assets/images/new/services/audio_call.svg";
        break;
      case 3:
        callTypeImagePath = "assets/images/new/services/phone_call.svg";
        break;
    }
    return callTypeImagePath;
  }

  String getCallTypeText() {
    String callTypeText = "";
    switch (widget.selectedCallType) {
      case 1:
        callTypeText = TranslationBase.of(context).videoCall;
        break;
      case 2:
        callTypeText = TranslationBase.of(context).audioCall;
        break;
      case 3:
        callTypeText = TranslationBase.of(context).phoneCall;
        break;
    }
    return callTypeText;
  }

  @override
  void dispose() {
    // cancelAPI();
    super.dispose();
  }

  Future<bool> askVideoCallPermission() async {
    bool result = false;
    if (Platform.isIOS) {
      if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted) || !(await Permission.location.request().isGranted)) {
        result = false;
      }
    } else {
      await showDialog(
          context: context,
          builder: (cxt) => CovidConsentDialog(
                okTitle: TranslationBase.of(context).acceptLbl,
                title: TranslationBase.of(context).covidConsentHeader,
                message: TranslationBase.of(context).liveCarePermissions,
                onTap: () async {
                  if (!(await Permission.notification.request().isGranted) ||
                      !(await Permission.camera.request().isGranted) ||
                      !(await Permission.microphone.request().isGranted) ||
                      !(await Permission.location.request().isGranted)) {
                    {
                      result = false;
                    }
                  }
                },
              ));
    }
    result = true;
    return result;
    // if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted) || !(await Permission.location.request().isGranted)) {
    //   return false;
    // }
    // return true;
  }

  openPermissionsDialog() {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).liveCarePermissions,
        okText: TranslationBase.of(context).settings,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () async {
          openAppSettings();
          Navigator.pop(context);
        },
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  openPermissionsConsentDialog() {
    showDialog(
        context: context,
        builder: (cxt) => CovidConsentDialog(
              okTitle: TranslationBase.of(context).acceptLbl,
              title: TranslationBase.of(context).covidConsentHeader,
              message: TranslationBase.of(context).covidConsent,
              onTap: () async {},
            ));
  }

  Future drawOverAppsMessageDialog(BuildContext context) async {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: TranslationBase.of(context).drawOverAppsPermission,
        okText: TranslationBase.of(context).confirm,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () async {
          await PlatformBridge.shared().askDrawOverAppsPermission();
          Navigator.pop(context);
        },
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  void cancelAPI() {
    LiveCareService service = new LiveCareService();
    service.cancelPharmaLiveCareRequest(widget.pharmaLiveCareClientID, context).then((res) {}).catchError((err) {
      print(err);
    });
  }

  onRadioChanged(int value) {
    setState(() {
      _selected = value;
    });
  }

  _getNormalText(text) {
    return Container(
      margin: EdgeInsets.only(top: 10.0, right: 10.0),
      child: Text(text, textAlign: TextAlign.start, style: TextStyle(fontSize: 14, letterSpacing: 0.5, color: Colors.black)),
    );
  }

  _getMarginText(text) {
    return Container(
      margin: EdgeInsets.only(top: 10.0, right: 10.0, bottom: 10.0),
      child: Text(text, textAlign: TextAlign.start, style: TextStyle(fontSize: 14, letterSpacing: 0.5, fontWeight: FontWeight.bold, color: Colors.black)),
    );
  }
}
