import 'dart:collection';

import 'package:device_calendar/device_calendar.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorListResponse.dart';
import 'package:hmg_patient_app/models/Appointments/DoctorRateDetails.dart';
import 'package:hmg_patient_app/models/Appointments/toDoCountProviderModel.dart';
import 'package:hmg_patient_app/models/header_model.dart';
import 'package:hmg_patient_app/pages/BookAppointment/BookConfirm.dart';
import 'package:hmg_patient_app/pages/BookAppointment/components/DocAvailableAppointments.dart';
import 'package:hmg_patient_app/pages/BookAppointment/waiting_appointment/waiting_appointment_info.dart';
import 'package:hmg_patient_app/pages/MyAppointments/SchedulePage.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.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/CalendarUtils.dart';
import 'package:hmg_patient_app/uitl/app_shared_preferences.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.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/widgets/buttons/custom_text_button.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/new_design/doctor_header.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_rating_bar/flutter_rating_bar.dart';
import 'package:provider/provider.dart';

import 'widgets/AppointmentActions.dart';

class AppointmentDetails extends StatefulWidget {
  AppoitmentAllHistoryResultList appo;
  static bool isLoading = false;
  dynamic doctorSchedule;
  static bool showFooterButton = false;
  final int? parentIndex;

  AppointmentDetails({required this.appo, this.parentIndex, this.doctorSchedule});

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

class _AppointmentDetailsState extends State<AppointmentDetails> with SingleTickerProviderStateMixin {
  static TabController? _tabController;

  AppSharedPreferences sharedPref = AppSharedPreferences();
  List<DoctorRateDetails> doctorDetailsList = [];

  ToDoCountProviderModel? toDoProvider;
  ProjectViewModel? projectViewModel;

  DoctorList doctorList = new DoctorList();

  @override
  void initState() {
    AppointmentDetails.showFooterButton = false;
    if (widget.doctorSchedule != null) {
      _tabController = new TabController(length: 2, vsync: this, initialIndex: 1);
      widget.appo.appointmentDate = widget.doctorSchedule['Date'];
    } else {
      _tabController = new TabController(length: 2, vsync: this);
    }
    doctorList.doctorID = widget.appo.doctorID;
    doctorList.clinicID = widget.appo.clinicID;
    doctorList.projectID = widget.appo.projectID;
    setTab();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _tabController!.dispose();
    AppointmentDetails.showFooterButton = false;
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);

    toDoProvider = Provider.of<ToDoCountProviderModel>(context);

    return AppScaffold(
      appBarTitle: widget.appo!.doctorNameObj!,
      isShowAppBar: true,
      showNewAppBar: true,
      backgroundColor: Colors.white,
      showNewAppBarTitle: true,
      bottomSheet: _bottomButtons(),
      body: SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            DoctorHeader(
              headerModel: HeaderModel(
                  widget.appo.doctorTitle! + " " + widget.appo.doctorNameObj!,
                  widget.appo.doctorID!,
                  widget.appo.doctorImageURL!,
                  widget.appo.doctorSpeciality!,
                  "",
                  widget.appo.projectName ?? "",
                  DateUtil.convertStringToDate(widget.appo.appointmentDate!),
                  widget.appo.isLiveCareAppointment! ? DateUtil.convertStringToDate(widget.appo.appointmentDate!).toString().split(" ")[1].substring(0, 5) : widget.appo.startTime!.substring(0, 5),
                  "",
                  widget.appo.doctorRate,
                  widget.appo.actualDoctorRate,
                  widget.appo.noOfPatientsRate,
                  "",
                  decimalDoctorRate: widget.appo.decimalDoctorRate.toString()
                  //model.user.emailAddress,
                  ),
              isNeedToShowButton: (widget.appo.clinicID == 17 ||
                      widget.appo.clinicID == 47 ||
                      widget.appo.clinicID == 23 ||
                      widget.appo.clinicID == 265 ||
                      widget.appo.clinicID == 134 ||
                      widget.appo.clinicID == 253 ||
                      widget.appo.isExecludeDoctor! ||
                      widget.appo.isLiveCareAppointment!)
                  ? false
                  : true,
              buttonTitle: TranslationBase.of(context).schedule,
              buttonIcon: 'assets/images/new/Boo_ Appointment.svg',
              showConfirmMessageDialog: false,
              onRatingAndReviewTap: getDoctorRatingsDetails,
              onTap: () {
                Navigator.push(
                  context,
                  FadePage(
                    page: SchedulePage(doctorList: doctorList, appo: widget.appo),
                  ),
                ).then((value) {
                  setState(() {
                    if (_tabController!.index == 0) {
                      _tabController!.animateTo((_tabController!.index + 1) % 2);
                      this.enableFooterButton();
                    }
                    widget.doctorSchedule = value;
                  });
                });
              },
            ),
            SizedBox(height: 10),
            Material(
              color: Color(0xffF8F8F8),
              child: TabBar(
                onTap: (index) {
                  setState(() {
                    if (index == 1) {
                      if (
                      // widget.appo.clinicID == 17 ||
                          widget.appo.clinicID == 47 ||
                          widget.appo.clinicID == 23 ||
                          widget.appo.clinicID == 253 ||
                          widget.appo.clinicID == 265 ||
                          widget.appo.clinicID == 134 ||
                          widget.appo.clinicID == 253 ||
                          widget.appo.isExecludeDoctor! ||
                          widget.appo.isLiveCareAppointment!) {
                        _tabController!.index = _tabController!.previousIndex;
                        AppointmentDetails.showFooterButton = false;
                      } else {
                        AppointmentDetails.showFooterButton = true;
                      }
                    }
                  });
                },
                tabs: [
                  Tab(child: Text(TranslationBase.of(context).appoActions, style: TextStyle(color: Colors.black))),
                  // widget.appo.clinicID == 17 ||
                          widget.appo.clinicID == 23 ||
                          widget.appo.clinicID == 47 ||
                          widget.appo.clinicID == 265 ||
                          widget.appo.clinicID == 253 ||
                          widget.appo.clinicID == 134 ||
                          widget.appo!.isExecludeDoctor! ||
                          widget.appo!.isLiveCareAppointment!
                      ? Tab(
                          child: Text(TranslationBase.of(context).availableAppo, style: TextStyle(color: Colors.grey)),
                        )
                      : Tab(
                          child: Text(TranslationBase.of(context).availableAppo, style: TextStyle(color: Colors.black)),
                        )
                ],
                controller: _tabController,
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height * 0.87,
              color: Color(0xffF8F8F8),
              child: TabBarView(
                physics: NeverScrollableScrollPhysics(),
                children: [
                  AppointmentActions(appo: widget.appo, tabController: _tabController!, enableFooterButton: enableFooterButton, projectViewModel: projectViewModel!),
                  DocAvailableAppointments(doctor: getDoctorObject(), doctorSchedule: widget.doctorSchedule, isLiveCareAppointment: widget.appo.isLiveCareAppointment!)
                ],
                controller: _tabController,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _bottomButtons() {
    if (widget.parentIndex == null) {
      return SizedBox();
    } else {
      List<Widget> list = [];
      if (widget.parentIndex == 0 && _tabController!.index == 0 && widget.appo.patientStatusType != 43) {
        list.add(
          Expanded(
            child: DefaultButton(
              TranslationBase.of(context).cancelAppointment,
              () {
                ConfirmDialog dialog = new ConfirmDialog(
                    context: context,
                    confirmMessage: TranslationBase.of(context).cancelAppoMsg,
                    okText: TranslationBase.of(context).confirm,
                    cancelText: TranslationBase.of(context).cancel_nocaps,
                    okFunction: cancelAppointment,
                    cancelFunction: () => {});
                dialog.showAlertDialog(context);
              },
              color: CustomColors.accentColor,
              textColor: CustomColors.white,
            ),
          ),
        );
        list.add(
          SizedBox(width: 8),
        );
        list.add(
          Expanded(
            child: DefaultButton(
              TranslationBase.of(context).confirm,
              confirmAppointment,
              color: Color(0xff359846),
            ),
          ),
        );
      } else if (widget.parentIndex == 1 && _tabController!.index == 0) {
        list.add(
          Expanded(
            child: DefaultButton(
              TranslationBase.of(context).cancelAppointment,
              () {
                ConfirmDialog dialog = new ConfirmDialog(
                    context: context,
                    confirmMessage: TranslationBase.of(context).cancelAppoMsg,
                    okText: TranslationBase.of(context).confirm,
                    cancelText: TranslationBase.of(context).cancel_nocaps,
                    okFunction: cancelAppointment,
                    cancelFunction: () => {});
                dialog.showAlertDialog(context);
              },
              color: CustomColors.accentColor,
              // textColor: Color(0xff000000),
            ),
          ),
        );
      } else if (_tabController!.index == 1) {
        list.add(
          Expanded(
            child: DefaultButton(
              TranslationBase.of(context).reviewAppointment,
              goToBookConfirm,
              // DocAvailableAppointments.areSlotsAvailable ? goToBookConfirm : null,
              color: Color(0xFFD02127),
              disabledColor: Color(0xff28323A).withOpacity(0.3),
            ),
          ),
        );
      }
      if (list.isEmpty) {
        return SizedBox();
      } else
        return Container(
          color: Colors.white,
          padding: EdgeInsets.only(top: 16, bottom: 16, right: 21, left: 21),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: list,
          ),
        );
    }
  }

  void enableFooterButton() {
    setState(() {
      AppointmentDetails.showFooterButton = true;
    });
  }

  void goToBookConfirm() {
    if (DocAvailableAppointments.selectedTime == TranslationBase.of(context).waitingAppointment) {
      canPayForWalkInAppointment();
    } else {
      if (DocAvailableAppointments.areSlotsAvailable)
        navigateToBookConfirm(context);
      else
        AppToast.showErrorToast(message: TranslationBase.of(context).selectSlot);
    }
  }

  canPayForWalkInAppointment() {
    DoctorsListService service = new DoctorsListService();
    GifLoaderDialogUtils.showMyDialog(context);
    service.canPayForWalkInAppointment(widget.appo.clinicID!, widget.appo.projectID!, widget.appo.doctorID!).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      navigateToWaitingAppointment(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err, localContext: context);
      print(err);
    });
  }

  Future navigateToWaitingAppointment(context) async {
    DoctorList doctor = new DoctorList();
    doctor.name = widget.appo.doctorNameObj;
    doctor.clinicID = widget.appo.clinicID;
    doctor.projectID = widget.appo.projectID;
    doctor.doctorID = widget.appo.doctorID;
    doctor.clinicName = widget.appo.clinicName;
    doctor.projectName = widget.appo.projectName;
    doctor.doctorTitle = widget.appo.doctorTitle;
    doctor.doctorImageURL = widget.appo.doctorImageURL;
    doctor.speciality = widget.appo.doctorSpeciality;
    doctor.nationalityFlagURL = "";
    doctor.doctorRate = widget.appo.doctorRate;
    doctor.noOfPatientsRate = widget.appo.noOfPatientsRate;

    projectViewModel?.setWaitingAppointmentProjectID(widget.appo.projectID!);
    projectViewModel?.setWaitingAppointmentDoctor(doctor);
    Navigator.push(
      context,
      FadePage(
        page: WaitingAppointmentInfo(),
      ),
    );
  }

  Future navigateToBookConfirm(context) async {
    Navigator.push(
      context,
      FadePage(
        page: BookConfirm(
          doctor: getDoctorObject(),
          isLiveCareAppointment: widget.appo.isLiveCareAppointment!,
          selectedDate: DocAvailableAppointments.selectedDate!,
          selectedTime: DocAvailableAppointments.selectedTime!,
          initialSlotDuration: 0,
          isWalkinAppointment: false,
        ),
      ),
    );
  }

  void getDoctorRatingsDetails() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.getDoctorsRatingDetails(widget.appo.doctorID, projectViewModel!.isArabic ? 1 : 2, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        doctorDetailsList.clear();
        res['DoctorRatingDetailsList'].forEach((v) {
          doctorDetailsList.add(new DoctorRateDetails.fromJson(v));
        });
        showRatingDialog(doctorDetailsList);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  void showRatingDialog(List<DoctorRateDetails> doctorDetailsList) {
    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: Dialog(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      // height: 400.0,
                      width: MediaQuery.of(context).size.width * 0.8,
                      color: Colors.white,
                      child: Column(
                        children: [
                          Container(
                              width: MediaQuery.of(context).size.width,
                              margin: EdgeInsets.only(bottom: 5.0),
                              padding: EdgeInsets.all(10.0),
                              child: Text(TranslationBase.of(context).doctorRating, style: TextStyle(fontSize: 22.0, color: Colors.black))),
                          Container(
                              margin: EdgeInsets.only(top: 0.0), child: Text(this.widget.appo.actualDoctorRate!.ceilToDouble().toString(), style: TextStyle(fontSize: 32.0, color: Colors.black))),
                          Container(
                              margin: EdgeInsets.only(top: 5.0),
                              alignment: Alignment.center,
                              child:
                                  // RatingBar.readOnly(
                                  //   initialRating: this.widget.appo.actualDoctorRate.toDouble(),
                                  //   size: 35.0,
                                  //   filledColor: Colors.yellow[700],
                                  //   emptyColor: Colors.grey[500],
                                  //   isHalfAllowed: true,
                                  //   halfFilledIcon: Icons.star_half,
                                  //   filledIcon: Icons.star,
                                  //   emptyIcon: Icons.star,
                                  // ),
                                  RatingBar(
                                initialRating: this.widget.appo.actualDoctorRate!.toDouble(),
                                direction: Axis.horizontal,
                                allowHalfRating: true,
                                itemCount: 5,
                                itemSize: 20,
                                ignoreGestures: true,
                                ratingWidget: RatingWidget(
                                  full: Icon(
                                    Icons.star,
                                    color: CustomColors.accentColor,
                                  ),
                                  half: Icon(
                                    Icons.star_half,
                                    color: CustomColors.accentColor,
                                  ),
                                  empty: Icon(
                                    Icons.star,
                                    color: CustomColors.accentColor,
                                  ),
                                ),
                                tapOnlyMode: true,
                                unratedColor: Colors.grey[500],
                                itemPadding: EdgeInsets.symmetric(horizontal: 4.0),
                                onRatingUpdate: (rating) {
                                  print(rating);
                                },
                              )),
                          Container(
                              margin: EdgeInsets.only(top: 10.0),
                              child: Text(this.widget.appo.noOfPatientsRate.toString() + " " + TranslationBase.of(context).reviews, style: TextStyle(fontSize: 14.0, color: Colors.black))),
                          Container(
                            margin: EdgeInsets.only(top: 10.0),
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).excellent, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Expanded(
                                  child: Container(
                                    margin: EdgeInsets.only(top: 10.0),
                                    child: SizedBox(
                                      width: getRatingWidth(doctorDetailsList[0].patientNumber),
                                      height: 6.0,
                                      child: Container(
                                        color: Colors.green[700],
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).v_good, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[1].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Color(0xffB7B723),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).good, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[2].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Color(0xffEBA727),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).average, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[3].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Color(0xffEB7227),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                Container(
                                    width: 100.0,
                                    margin: EdgeInsets.only(top: 10.0, left: 15.0, right: 15.0),
                                    child: Text(TranslationBase.of(context).below_average, style: TextStyle(fontSize: 13.0, color: Colors.black))),
                                Container(
                                  margin: EdgeInsets.only(top: 10.0),
                                  child: SizedBox(
                                    width: getRatingWidth(doctorDetailsList[4].patientNumber),
                                    height: 6.0,
                                    child: Container(
                                      color: Color(0xffE20C0C),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Container(margin: EdgeInsets.only(top: 40.0), child: Divider()),
                          Container(
                            margin: EdgeInsets.only(top: 0.0),
                            child: Align(
                              alignment: FractionalOffset.bottomCenter,
                              child: ButtonTheme(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10.0),
                                ),
                                minWidth: MediaQuery.of(context).size.width,
                                height: 40.0,
                                child: CustomTextButton(
                                  elevation: 0.0,
                                  backgroundColor: Colors.white,
                                  disabledForegroundColor: new Color(0xFFbcc2c4).withOpacity(0.38),
                                  disabledBackgroundColor: new Color(0xFFbcc2c4).withOpacity(0.12),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                  child: Text(TranslationBase.of(context).cancel, style: TextStyle(fontSize: 18.0, color: Colors.red)),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
        transitionDuration: Duration(milliseconds: 500),
        barrierDismissible: true,
        barrierLabel: '',
        context: context,
        pageBuilder: (context, animation1, animation2) {
          return SizedBox();
        });
  }

  double getRatingWidth(int patientNumber) {
    var width = (patientNumber / this.widget.appo.noOfPatientsRate!) * 100;
    return width;
  }

  String getDate(String date) {
    DateTime dateObj = DateUtil.convertStringToDate(date);
    return DateUtil.getWeekDay(dateObj.weekday) + ", " + dateObj.day.toString() + " " + DateUtil.getMonth(dateObj.month) + " " + dateObj.year.toString();
  }

  String getDoctorSpeciality(List<String> docSpecial) {
    String docSpeciality = "";
    docSpecial.forEach((v) {
      docSpeciality = docSpeciality + v + " ";
    });
    return docSpeciality;
  }

  DoctorList getDoctorObject() {
    DoctorList docObj = new DoctorList();
    docObj.doctorID = widget.appo.doctorID;
    docObj.clinicID = widget.appo.clinicID;
    docObj.projectID = widget.appo.projectID;
    docObj.doctorTitle = widget.appo.doctorTitle;
    docObj.name = widget.appo.doctorNameObj;
    docObj.clinicName = widget.appo.clinicName;
    docObj.speciality = widget.appo.doctorSpeciality;
    docObj.actualDoctorRate = widget.appo.actualDoctorRate;
    docObj.projectName = widget.appo.projectName;
    docObj.originalClinicID = widget.appo.originalClinicID;
    docObj.doctorImageURL = widget.appo.doctorImageURL;
    return docObj;
  }

  void openSchedule() {
    Navigator.push(
        context,
        FadePage(
            page: SchedulePage(
          doctorList: getDoctorObject(),
          appo: widget.appo,
        )));
  }

  setTab() async {
    var scheduleDoctor = await sharedPref.getObject(DOCTOR_SCHEDULE_DATE_SEL);
    if (scheduleDoctor != null) widget.appo.appointmentDate = scheduleDoctor['Date'];
  }

  confirmAppointment() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.confirmAppointment(widget.appo.appointmentNo!, widget.appo.clinicID!, widget.appo.projectID!, widget.appo.isLiveCareAppointment!, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
        Navigator.of(context).pop();
        projectViewModel!.analytics.appointment.appointment_details_confirm(appointment: widget.appo);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  checkIfHasReminder() async {
    CalendarUtils calendarUtils = await CalendarUtils.getInstance();

    DateTime startEventsDate = DateUtil.convertStringToDate(widget.appo.appointmentDate!);
    DateTime endEventsDate = DateUtil.convertStringToDate(widget.appo.appointmentDate!);
    RetrieveEventsParams params = new RetrieveEventsParams(startDate: startEventsDate, endDate: endEventsDate);
    if (calendarUtils.calendars.length > 1) {
      calendarUtils.calendars.forEach((calender) {
        calendarUtils.retrieveEvents(calender.id!, params).then((value) {
          Result<UnmodifiableListView<Event>> events = value;
          events.data!.forEach((element) {
            if (element.title!.contains(widget.appo.doctorNameObj!)) calendarUtils.deleteEvent(calender, element);
          });
        });
      });
    } else {
      await calendarUtils.retrieveEvents(calendarUtils.calendars[0].id!, params).then((value) {
        Result<UnmodifiableListView<Event>> events = value;
        events.data!.forEach((element) {
          if (element.title!.contains(widget.appo.doctorNameObj!)) calendarUtils.deleteEvent(calendarUtils.calendars[0], element);
        });
      });
    }
  }

  cancelAppointment() {
    ConfirmDialog.closeAlertDialog(context);
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    service.cancelAppointment(widget.appo, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        checkIfHasReminder();
        getToDoCount();
        AppToast.showSuccessToast(message: res['ErrorEndUserMessage']);
        Navigator.of(context).pop();
        projectViewModel!.analytics.appointment.appointment_details_cancel(appointment: widget.appo);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
      projectViewModel!.analytics.appointment.appointment_details_cancel(appointment: widget.appo, appointment_type: widget.appo!.isLiveCareAppointment! ? "livecare" : "regular");
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
    });
  }

  getToDoCount() {
    toDoProvider!.setState(0, 0, true, toDoProvider!.notificationsCount);
    ClinicListService service = new ClinicListService();
    service.getActiveAppointmentNo(context).then((res) {
      if (res['MessageStatus'] == 1) {
        // toDoProvider.setState(res['AppointmentActiveNumber'], true, toDoProvider.notificationsCount);
        toDoProvider!.setState(res['AppointmentActiveNumber'], res['AncillaryOrderListCount'], true, toDoProvider!.notificationsCount);
      } else {}
    }).catchError((err) {
      print(err);
    });
  }
}
