import 'dart:io';

import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/LiveCare/ERAppointmentFeesResponse.dart';
import 'package:diplomaticquarterapp/services/livecare_services/livecare_provider.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/PlatformBridge.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/location_util.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/covid_consent_dialog.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.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;

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

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

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

  ProjectViewModel projectViewModel;
  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,
      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: 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: 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: 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,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10.0),
                      child: Row(
                        children: <Widget>[
                          Radio(
                            value: 1,
                            groupValue: _selected,
                            onChanged: onRadioChanged,
                          ),
                          Text(
                            TranslationBase.of(context).agreeTo,
                            style: new TextStyle(
                              fontSize: 12.0,
                              fontWeight: FontWeight.w600,
                              letterSpacing: -0.48,
                              color: CustomColors.textColor,
                            ),
                          ),
                          mWidth(4),
                          InkWell(
                            onTap: () {
                              launch("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,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    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: 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 {
                          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,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<bool> askVideoCallPermission() async {
    if (Platform.isIOS) {
      if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted) || !(await Permission.location.request().isGranted)) {
        return 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)) {
                    return false;
                  }
                },
              ));
    }
    return true;
    // 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);
    });
  }

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