import 'dart:io';

import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/models/Appointments/DoctorListResponse.dart';
import 'package:diplomaticquarterapp/models/Authentication/authenticated_user.dart';
import 'package:diplomaticquarterapp/models/LiveCare/ERAppointmentFeesResponse.dart';
import 'package:diplomaticquarterapp/models/LiveCare/LiveCareClinicsListResponse.dart';
import 'package:diplomaticquarterapp/models/LiveCare/LiveCareScheduleClinicsListResponse.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/SearchResults.dart';
import 'package:diplomaticquarterapp/pages/ToDoList/payment_method_select.dart';
import 'package:diplomaticquarterapp/pages/livecare/livecare_home.dart';
import 'package:diplomaticquarterapp/pages/livecare/livecare_scheduling/schedule_clinic_card.dart';
import 'package:diplomaticquarterapp/pages/livecare/livecare_type_select.dart';
import 'package:diplomaticquarterapp/pages/livecare/widgets/clinic_card.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.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_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/custom_text_button.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:diplomaticquarterapp/widgets/in_app_browser/InAppBrowser.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../live_care_payment_page.dart';

class ClinicList extends StatefulWidget {
  final Function getLiveCareHistory;
  bool isPharmacyLiveCare;
  String pharmacyLiveCareQRCode;

  ClinicList({@required this.getLiveCareHistory, this.isPharmacyLiveCare = false, this.pharmacyLiveCareQRCode = ""});

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

class _clinic_listState extends State<ClinicList> {
  int currentSelectedIndex = 0;
  LiveCareClinicsListResponse liveCareClinicsListResponse;

  List<PatientERGetClinicsList> liveCareOnlineClinicsListResponse;
  List<PatientERGetClinicsList> liveCareOfflineClinicsListResponse;

  LiveCareScheduleClinicsListResponse liveCareScheduleClinicsListResponse;

  bool isDataLoaded = false;
  var languageID;
  var currentSelectedLiveCareType;

  int selectedClinicID;
  String selectedClinicName = "-";

  AppSharedPreferences sharedPref = AppSharedPreferences();

  AuthenticatedUser authUser;
  AuthProvider authProvider = new AuthProvider();

  MyInAppBrowser browser;

  String liveCareClinicIDs;

  ProjectViewModel projectViewModel;

  String selectedPaymentMethod = "";
  String amount = "";

  String tamaraPaymentStatus;
  String tamaraOrderID;
  String selectedInstallmentPlan;

  @override
  void initState() {
    liveCareClinicsListResponse = new LiveCareClinicsListResponse();

    liveCareOnlineClinicsListResponse = new List();
    liveCareOfflineClinicsListResponse = new List();

    liveCareScheduleClinicsListResponse = new LiveCareScheduleClinicsListResponse();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (LiveCareHome.isLiveCareTypeSelected != true) {
        openLiveCareSelectionDialog();
      } else {
        setState(() {
          currentSelectedLiveCareType = "immediate";
          getLiveCareClinicsList();
        });
      }
    });

    getLanguageID();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return Container(
      child: currentSelectedLiveCareType == "immediate" ? getLiveCareImmediateClinicList() : getLiveCareScheduleClinicList(),
    );
  }

  void startLiveCare() {
    bool isError = false;
    LiveCareService service = new LiveCareService();
    GifLoaderDialogUtils.showMyDialog(context);
    ERAppointmentFeesResponse erAppointmentFeesResponse = new ERAppointmentFeesResponse();
    service.getERAppointmentFees(selectedClinicID, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['HasAppointment'] == true) {
        isError = true;
        showLiveCareCancelDialog(res['ErrorEndUserMessage'], res);
      } else {
        erAppointmentFeesResponse = ERAppointmentFeesResponse.fromJson(res);
        isError = false;
      }
      if (!isError) getERAppointmentTime(erAppointmentFeesResponse.getERAppointmentFeesList);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      isError = true;
      AppToast.showErrorToast(message: err);
    });
    projectViewModel.analytics.liveCare.livecare_immediate_consultation_clinic(clinic: selectedClinicName);
  }

  showLiveCareCancelDialog(String msg, res) {
    ConfirmDialog dialog = new ConfirmDialog(
        context: context,
        confirmMessage: msg,
        okText: TranslationBase.of(context).confirm,
        cancelText: TranslationBase.of(context).cancel_nocaps,
        okFunction: () => {cancelAppointment(res)},
        cancelFunction: () => {});
    dialog.showAlertDialog(context);
  }

  cancelAppointment(res) {
    AppoitmentAllHistoryResultList appo = AppoitmentAllHistoryResultList();
    appo.clinicID = res['ClinicID'];
    appo.doctorID = res['DoctorID'];
    appo.endTime = res['EndTime'];
    appo.projectID = res['ProjectID'];
    appo.startTime = res['StrAppointmentDate'];
    appo.appointmentNo = res['AppointmentID'];
    appo.isLiveCareAppointment = true;
    appo.originalClinicID = 0;
    appo.originalProjectID = res['ProjectID'];
    appo.appointmentDate = res['AppointmentDate'];

    ConfirmDialog.closeAlertDialog(context);
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.cancelAppointment(appo, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      print(res);
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
        startLiveCare();
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  getERAppointmentTime(GetERAppointmentFeesList getERAppointmentFeesList) {
    LiveCareService service = new LiveCareService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getERAppointmentTime(selectedClinicID, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      showLiveCarePaymentDialog(getERAppointmentFeesList, res['WatingtimeInteger']);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err);
    });
  }

  showLiveCarePaymentDialog(GetERAppointmentFeesList getERAppointmentFeesList, int waitingTime) {
    navigateTo(context, LiveCarePatmentPage(getERAppointmentFeesList: getERAppointmentFeesList, waitingTime: waitingTime, clinicName: selectedClinicName, isPharmaLiveCare: widget.isPharmacyLiveCare, pharmaLiveCareClientID: widget.pharmacyLiveCareQRCode)).then(
      (value) {
        if (value) {
          if (getERAppointmentFeesList.total == "0" || getERAppointmentFeesList.total == "0.0") {
            addNewCallForPatientER(projectViewModel.user.patientID.toString() + "" + DateTime.now().millisecondsSinceEpoch.toString());
          } else {
            navigateToPaymentMethod(getERAppointmentFeesList, context);
          }

          // askVideoCallPermission().then((value) {
          //   if (value) {
          //     if (getERAppointmentFeesList.total == "0" || getERAppointmentFeesList.total == "0.0") {
          //       addNewCallForPatientER(projectViewModel.user.patientID.toString() + "" + DateTime.now().millisecondsSinceEpoch.toString());
          //     } else {
          //       navigateToPaymentMethod(getERAppointmentFeesList, context);
          //     }
          //   }
          // });
        } else {
          Navigator.pop(context);
        }
      },
    );
  }

  Future<bool> askVideoCallPermission() async {
    if (!(await Permission.camera.request().isGranted) || !(await Permission.microphone.request().isGranted)) {
      return false;
    }
    if (Platform.isAndroid && !(await PlatformBridge.shared().isDrawOverAppsPermissionAllowed())) {
      await drawOverAppsMessageDialog(context);
      return false;
    }
    return true;
  }

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

  // showLiveCareInfoDialog(GetERAppointmentFeesList getERAppointmentFeesList) async {
  //   if (await this.sharedPref.getObject(USER_PROFILE) != null) {
  //     var data = AuthenticatedUser.fromJson(await this.sharedPref.getObject(USER_PROFILE));
  //     setState(() {
  //       authUser = data;
  //     });
  //   }
  //
  //   showGeneralDialog(
  //           barrierColor: Colors.black.withOpacity(0.5),
  //           transitionBuilder: (context, a1, a2, widget) {
  //             final curvedValue = Curves.easeInOutBack.transform(a1.value) - 1.0;
  //             return Transform(
  //               transform: Matrix4.translationValues(0.0, curvedValue * 200, 0.0),
  //               child: Opacity(
  //                 opacity: a1.value,
  //                 child: LiveCareInfoDialog(),
  //               ),
  //             );
  //           },
  //           transitionDuration: Duration(milliseconds: 500),
  //           barrierDismissible: true,
  //           barrierLabel: '',
  //           context: context,
  //           pageBuilder: (context, animation1, animation2) {})
  //       .then((value) {
  //     if (value) {
  //       if (getERAppointmentFeesList.total == "0" || getERAppointmentFeesList.total == "0.0") {
  //         addNewCallForPatientER(authUser.patientID.toString() + "" + DateTime.now().millisecondsSinceEpoch.toString());
  //       } else {
  //         navigateToPaymentMethod(getERAppointmentFeesList, context);
  //       }
  //     }
  //   });
  // }

  Future navigateToPaymentMethod(GetERAppointmentFeesList getERAppointmentFeesList, context) async {
    AppoitmentAllHistoryResultList appo = new AppoitmentAllHistoryResultList();

    appo.clinicID = selectedClinicID;
    appo.appointmentNo = DateTime.now().millisecondsSinceEpoch;
    appo.projectID = 12;

    if (await this.sharedPref.getObject(USER_PROFILE) != null) {
      var data = AuthenticatedUser.fromJson(await this.sharedPref.getObject(USER_PROFILE));
      setState(() {
        authUser = data;
      });
    }

    bool isPharmacyLiveCare = widget.isPharmacyLiveCare;
    String pharmaLiveCareQRCodeValue = widget.pharmacyLiveCareQRCode;

    Navigator.push(
        context,
        FadePage(
            page: PaymentMethod(
          onSelectedMethod: (String metohd, [String selectedInstallmentPlan]) {
            setState(() {});
          },
          patientShare: num.parse(getERAppointmentFeesList.total),
          isFromAdvancePayment: widget.isPharmacyLiveCare,
        ))).then((value) {
      print(value);
      widget.isPharmacyLiveCare = isPharmacyLiveCare;
      widget.pharmacyLiveCareQRCode = pharmaLiveCareQRCodeValue;
      if (value != null) {
        openPayment(value, authUser, num.parse(getERAppointmentFeesList.total), appo);
        projectViewModel.analytics.liveCare.payment_method(appointment_type: 'livecare', clinic: selectedClinicName, payment_method: value[0], payment_type: 'appointment');
      }
    });
  }

  openPayment(List<String> paymentMethod, AuthenticatedUser authenticatedUser, num amount, AppoitmentAllHistoryResultList appo) {
    browser = new MyInAppBrowser(onExitCallback: onBrowserExit, appo: appo, onLoadStartCallback: onBrowserLoadStart, context: context);

    selectedPaymentMethod = paymentMethod[0];
    selectedInstallmentPlan = paymentMethod[1];
    this.amount = amount.toString();

    browser.openPaymentBrowser(
        amount,
        "LiveCare Payment",
        widget.isPharmacyLiveCare ? widget.pharmacyLiveCareQRCode : Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo),
        "12",
        authenticatedUser.emailAddress,
        paymentMethod[0],
        authenticatedUser.patientType,
        authenticatedUser.firstName,
        authenticatedUser.patientID,
        authenticatedUser,
        browser,
        false,
        "4",
        selectedClinicID,
        context,
        "",
        "",
        "",
        "",
        paymentMethod[1]);
  }

  onBrowserLoadStart(String url) {
    print("onBrowserLoadStart");
    print(url);

    if (selectedPaymentMethod == "TAMARA") {
      if (Platform.isAndroid) {
        Uri uri = new Uri.dataFromString(url);
        tamaraPaymentStatus = uri.queryParameters['status'];
        tamaraOrderID = uri.queryParameters['AuthorizePaymentId'];
      } else {
        Uri uri = new Uri.dataFromString(url);
        tamaraPaymentStatus = uri.queryParameters['paymentStatus'];
        tamaraOrderID = uri.queryParameters['orderId'];
      }
    }

    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!!!!");
    try {
      if (selectedPaymentMethod == "TAMARA") {
        checkTamaraPaymentStatus(Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), appo);
        // if (tamaraPaymentStatus != null && tamaraPaymentStatus.toLowerCase() == "approved") {
        //   updateTamaraRequestStatus("success", "14", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID, num.parse(selectedInstallmentPlan), appo);
        // } else {
        //   updateTamaraRequestStatus(
        //       "Failed", "00", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID != null ? tamaraOrderID : "", num.parse(selectedInstallmentPlan), appo);
        // }
      } else {
        checkPaymentStatus(appo);
      }
    } catch (err) {
      print(err);
    }
  }

  checkTamaraPaymentStatus(String orderID, AppoitmentAllHistoryResultList appo) {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getTamaraPaymentStatus(orderID).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res["status"].toString().toLowerCase() == "success") {
        updateTamaraRequestStatus("success", "14", orderID, tamaraOrderID, num.parse(selectedInstallmentPlan), appo);
      } else {
        updateTamaraRequestStatus(
            "Failed", "00", Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), tamaraOrderID != null ? tamaraOrderID : "", num.parse(selectedInstallmentPlan), appo);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  updateTamaraRequestStatus(String responseMessage, String status, String clientRequestID, String tamaraOrderID, int selectedInstallments, AppoitmentAllHistoryResultList appo) {
    final currency = projectViewModel.user.outSA == 0 ? "sar" : 'aed';
    GifLoaderDialogUtils.showMyDialog(context);
    try {
      DoctorsListService service = new DoctorsListService();
      service.updateTamaraRequestStatus(responseMessage, status, clientRequestID, tamaraOrderID, selectedInstallments).then((res) {
        GifLoaderDialogUtils.hideDialog(context);
        if (tamaraPaymentStatus != null && tamaraPaymentStatus.toLowerCase() == "approved") {
          addNewCallForPatientER(Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo));
        } else {
          AppToast.showErrorToast(message: res['Response_Message']);
          projectViewModel.analytics.liveCare.livecare_immediate_consultation_payment_failed(
              appointment_type: 'livecare',
              payment_type: 'appointment',
              payment_method: selectedPaymentMethod,
              txn_amount: this.amount,
              txn_currency: currency,
              error_message: res['Response_Message']);
        }
      }).catchError((err) {
        print(err);
        AppToast.showErrorToast(message: err);
        GifLoaderDialogUtils.hideDialog(context);
      });
    } catch (err) {
      print(err);
    }
  }

  checkPaymentStatus(AppoitmentAllHistoryResultList appo) {
    String amount;
    String payment_method;
    final currency = projectViewModel.user.outSA == 0 ? "sar" : 'aed';
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.checkPaymentStatus(widget.isPharmacyLiveCare ? widget.pharmacyLiveCareQRCode : Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo), context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      String paymentInfo = res['Response_Message'];
      amount = res['Amount'].toString();
      payment_method = res['PaymentMethod'];
      if (paymentInfo == 'Success') {
        addNewCallForPatientER(widget.isPharmacyLiveCare ? widget.pharmacyLiveCareQRCode : Utils.getAppointmentTransID(appo.projectID, appo.clinicID, appo.appointmentNo));
      } else {
        AppToast.showErrorToast(message: res['Response_Message']);
        projectViewModel.analytics.liveCare.livecare_immediate_consultation_payment_failed(
            appointment_type: 'livecare', payment_type: 'appointment', payment_method: selectedPaymentMethod, txn_amount: this.amount, txn_currency: currency, error_message: res['Response_Message']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  addNewCallForPatientER(String clientRequestID) {
    LiveCareService service = new LiveCareService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.addNewCallForPatientER(selectedClinicID, clientRequestID, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showSuccessToast(message: "New Call has been added successfully");
      widget.getLiveCareHistory();
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  getLanguageID() async {
    languageID = await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar');
  }

  getLiveCareClinicsList() {
    isDataLoaded = false;
    LiveCareService service = new LiveCareService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getLivecareClinics(context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      print(res['PatientER_GetClinicsList'].length);
      if (res['MessageStatus'] == 1) {
        setState(() {
          liveCareOnlineClinicsListResponse.clear();
          liveCareClinicsListResponse = LiveCareClinicsListResponse.fromJson(res);

          liveCareClinicsListResponse.patientERGetClinicsList.forEach((clinic) {
            if (clinic.isOnline == 1) {
              liveCareOnlineClinicsListResponse.add(clinic);
            } else {
              liveCareOfflineClinicsListResponse.add(clinic);
            }
          });
          if (liveCareClinicIDs != null) {
            selectedClinicID = int.parse(liveCareClinicIDs.split("-")[2]);
            selectedClinicName = liveCareClinicIDs.split("-")[0];
          } else {
            selectedClinicID = liveCareClinicsListResponse.patientERGetClinicsList[0].serviceID;
            selectedClinicName = liveCareClinicsListResponse.patientERGetClinicsList[0].serviceName;
          }
          isDataLoaded = true;
        });
      } else {
        isDataLoaded = true;
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  getLiveCareScheduleClinicsList() {
    isDataLoaded = false;
    LiveCareService service = new LiveCareService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.getLiveCareScheduledClinics(context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      print(res['ClinicsHaveScheduleList'].length);
      if (res['MessageStatus'] == 1) {
        setState(() {
          liveCareScheduleClinicsListResponse = LiveCareScheduleClinicsListResponse.fromJson(res);
          selectedClinicID = liveCareScheduleClinicsListResponse.clinicsHaveScheduleList[0].serviceID;
          selectedClinicName = liveCareScheduleClinicsListResponse.clinicsHaveScheduleList[0].clinicDesc;
          isDataLoaded = true;
        });
      } else {
        isDataLoaded = true;
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  openLiveCareSelectionDialog() async {
    liveCareClinicIDs = await sharedPref.getString(LIVECARE_CLINIC_DATA);
    sharedPref.remove(LIVECARE_CLINIC_DATA);
    if (liveCareClinicIDs != null) {
      selectedClinicID = int.parse(liveCareClinicIDs.split("-")[2]);
      setState(() {
        currentSelectedLiveCareType = "immediate";
      });
      // if(widget.isPharmacyLiveCare) {
      //
      // } else {
      getLiveCareClinicsList();
      startLiveCare();
      // }
    } else {
      Navigator.of(context)
          .push(new MaterialPageRoute<String>(
              builder: (BuildContext context) {
                return LiveCareTypeSelect();
              },
              fullscreenDialog: true))
          .then((value) async {
        if (value == null) {
          Navigator.pop(context);
        } else if (value.contains("/")) {
          widget.isPharmacyLiveCare = true;
          widget.pharmacyLiveCareQRCode = value.split("/")[1];
          liveCareClinicIDs = await sharedPref.getString(LIVECARE_CLINIC_DATA);
          selectedClinicID = 1;
          selectedClinicName = TranslationBase.of(context).pharmaLiveCare;
          sharedPref.remove(LIVECARE_CLINIC_DATA);
          startLiveCare();
        } else {
          print(value);
          if (value == "immediate") {
            setState(() {
              LiveCareHome.isLiveCareTypeSelected = true;
              currentSelectedLiveCareType = "immediate";
            });
            getLiveCareClinicsList();
          }
          if (value == "schedule") {
            setState(() {
              LiveCareHome.isLiveCareTypeSelected = true;
              currentSelectedLiveCareType = "schedule";
            });
            getLiveCareScheduleClinicsList();
          }
        }
      });
    }
  }

  Widget getLiveCareScheduleClinicList() {
    return Column(
      children: <Widget>[
        isDataLoaded
            ? Expanded(
                child: Container(
                  child: liveCareScheduleClinicsListResponse.clinicsHaveScheduleList.length > 0
                      ? Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            mHeight(10),
                            ListView.builder(
                              scrollDirection: Axis.vertical,
                              shrinkWrap: true,
                              physics: ScrollPhysics(),
                              padding: EdgeInsets.all(0.0),
                              itemCount: liveCareScheduleClinicsListResponse.clinicsHaveScheduleList.length,
                              itemBuilder: (context, index) {
                                return InkWell(
                                  onTap: () {
                                    updateSelectedScheduleIndex(liveCareScheduleClinicsListResponse.clinicsHaveScheduleList[index]);
                                  },
                                  child: ScheduleClinicCard(
                                    isSelected: selectedClinicID == liveCareScheduleClinicsListResponse.clinicsHaveScheduleList[index].serviceID ? true : false,
                                    clinicsHaveScheduleList: liveCareScheduleClinicsListResponse.clinicsHaveScheduleList[index],
                                    languageID: languageID,
                                  ),
                                );
                              },
                            ),
                            Container(
                              height: 10.0,
                            ),
                          ],
                        )
                      : getNoDataWidget(context),
                ),
              )
            : Container(),
        isDataLoaded
            ? Container(
                width: double.infinity,
                color: Colors.white,
                padding: EdgeInsets.all(12),
                child: ButtonTheme(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  minWidth: MediaQuery.of(context).size.width * 0.7,
                  height: 45.0,
                  child: CustomTextButton(
                    backgroundColor: CustomColors.accentColor,
                    disabledForegroundColor: Color(0xFFbcc2c4).withOpacity(0.38),
                    disabledBackgroundColor: Color(0xFFbcc2c4).withOpacity(0.12),
                    elevation: 0,
                    onPressed: startScheduleLiveCare,
                    child: Text(TranslationBase.of(context).start, style: TextStyle(fontSize: 18.0, color: Colors.white)),
                  ),
                ),
              )
            : Container(),
      ],
    );
  }

  Widget getLiveCareImmediateClinicList() {
    return Column(
      children: <Widget>[
        isDataLoaded
            ? Expanded(
                child: Container(
                  child: SingleChildScrollView(
                      child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      ListView.builder(
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true,
                        physics: ScrollPhysics(),
                        padding: const EdgeInsets.only(top: 16.0),
                        itemCount: liveCareOnlineClinicsListResponse.length,
                        itemBuilder: (context, index) {
                          return InkWell(
                            onTap: () {
                              updateSelectedIndex(liveCareOnlineClinicsListResponse[index]);
                            },
                            child: ClinicCard(
                              isSelected: selectedClinicID == liveCareOnlineClinicsListResponse[index].serviceID ? true : false,
                              patientERGetClinicsList: liveCareOnlineClinicsListResponse[index],
                              languageID: languageID,
                            ),
                          );
                        },
                      ),
                      ListView.builder(
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true,
                        physics: ScrollPhysics(),
                        padding: EdgeInsets.all(0.0),
                        itemCount: liveCareOfflineClinicsListResponse.length,
                        itemBuilder: (context, index) {
                          return ClinicCard(
                            isSelected: selectedClinicID == liveCareOfflineClinicsListResponse[index].serviceID ? true : false,
                            patientERGetClinicsList: liveCareOfflineClinicsListResponse[index],
                            languageID: languageID,
                          );
                        },
                      ),
                      Container(
                        height: 10.0,
                      ),
                    ],
                  )),
                ),
              )
            : Container(),
        isDataLoaded
            ? Container(
                color: Colors.white,
                width: double.infinity,
                padding: EdgeInsets.all(16),
                child: DefaultButton(
                  TranslationBase.of(context).start,
                  () {
                    startLiveCare();
                  },
                ),
              )
            : Container(),
      ],
    );
  }

  void startScheduleLiveCare() {
    List<DoctorList> doctorsList = [];
    LiveCareService service = new LiveCareService();
    GifLoaderDialogUtils.showMyDialog(context);
    List<PatientDoctorAppointmentList> _patientDoctorAppointmentListHospital = List();
    service.getLiveCareScheduledDoctorList(context, selectedClinicID).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['DoctorByClinicIDList'].length != 0) {
            res['DoctorByClinicIDList'].forEach((v) {
              doctorsList.add(new DoctorList.fromJson(v));
            });

            doctorsList.forEach((element) {
              List<PatientDoctorAppointmentList> doctorByHospital = _patientDoctorAppointmentListHospital
                  .where(
                    (elementClinic) => elementClinic.filterName == element.projectName,
                  )
                  .toList();

              if (doctorByHospital.length != 0) {
                _patientDoctorAppointmentListHospital[_patientDoctorAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList.add(element);
              } else {
                _patientDoctorAppointmentListHospital
                    .add(PatientDoctorAppointmentList(filterName: element.projectName, distanceInKMs: element.projectDistanceInKiloMeters.toString(), patientDoctorAppointment: element));
              }
            });
          } else {}
        });
        this.sharedPref.setBool(IS_LIVECARE_APPOINTMENT, true);
        navigateToSearchResults(context, doctorsList, _patientDoctorAppointmentListHospital);
      } else {}
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
    projectViewModel.analytics.liveCare.livecare_schedule_video_call_clinic(clinic: selectedClinicName);
  }

  Future navigateToSearchResults(context, List<DoctorList> docList, List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital) async {
    Navigator.push(context, FadePage(page: SearchResults(doctorsList: docList, isLiveCareAppointment: false, patientDoctorAppointmentListHospital: patientDoctorAppointmentListHospital)));
  }

  updateSelectedIndex(PatientERGetClinicsList patientERGetClinicsList) {
    setState(() {
      selectedClinicID = patientERGetClinicsList.serviceID;
      selectedClinicName = patientERGetClinicsList.serviceName;
    });
  }

  updateSelectedScheduleIndex(ClinicsHaveScheduleList patientERGetClinicsList) {
    setState(() {
      selectedClinicID = patientERGetClinicsList.serviceID;
      selectedClinicName = patientERGetClinicsList.clinicDesc;
    });
  }
}
