import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/core/enum/filter_type.dart';
import 'package:hmg_patient_app/core/model/ImagesInfo.dart';
import 'package:hmg_patient_app/core/service/AuthenticatedUserObject.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:hmg_patient_app/models/Appointments/toDoCountProviderModel.dart';
import 'package:hmg_patient_app/pages/MyAppointments/models/AppointmentType.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/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/data_display/medical/doctor_card.dart';
import 'package:hmg_patient_app/widgets/new_design/my_tab_view.dart';
import 'package:hmg_patient_app/widgets/others/app_expandable_notifier.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:provider/provider.dart';

import 'AppointmentDetails.dart';

class MyAppointments extends StatefulWidget {
  @override
  _MyAppointmentsState createState() => _MyAppointmentsState();
}

class _MyAppointmentsState extends State<MyAppointments> with SingleTickerProviderStateMixin {
  List<AppoitmentAllHistoryResultList> upcomingAppoList = [];
  List<AppoitmentAllHistoryResultList> arrivedAppoListNew = [];

  List<AppoitmentAllHistoryResultList> bookedAppoList = [];
  List<AppoitmentAllHistoryResultList> confirmedAppoList = [];
  List<AppoitmentAllHistoryResultList> arrivedAppoList = [];

  List<PatientAppointmentList> _patientBookedAppointmentListHospital = [];
  List<PatientAppointmentList> _patientConfirmedAppointmentListHospital = [];
  List<PatientAppointmentList> _patientArrivedAppointmentListHospital = [];

  List<PatientAppointmentList> _patientBookedAppointmentListClinic = [];
  List<PatientAppointmentList> _patientConfirmedAppointmentListClinic = [];
  List<PatientAppointmentList> _patientArrivedAppointmentListClinic = [];

  List<PatientAppointmentList> _patientBookedAndConfirmedAppointmentListHospital = [];
  List<PatientAppointmentList> _patientBookedAndConfirmedAppointmentListClinic = [];

  bool isDataLoaded = false;
  var sharedPref = new AppSharedPreferences();
  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();

  List<ImagesInfo> imagesInfo = [];

  FilterType? filterType;

  int _currentPage = 1;

  ToDoCountProviderModel? toDoProvider;
  ProjectViewModel? projectViewModel;

  @override
  void initState() {
    filterType = FilterType.Clinic;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (Provider.of<ProjectViewModel>(context, listen: false).isLogin) getPatientAppointmentHistory(true, false);
    });
    imagesInfo.add(ImagesInfo(
        imageEn: 'https://hmgwebservices.com/Images/MobileApp/imges-info/my-appointment/en/0.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/imges-info/my-appointment/ar/0.png'));
    imagesInfo.add(ImagesInfo(
        imageEn: 'https://hmgwebservices.com/Images/MobileApp/imges-info/my-appointment/en/1.png', imageAr: 'https://hmgwebservices.com/Images/MobileApp/imges-info/my-appointment/ar/1.png'));
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of<ProjectViewModel>(context);
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).myAppointmentsList,
      isShowAppBar: true,
      imagesInfo: imagesInfo,
      showNewAppBar: true,
      backgroundColor: Color(0xffF8F8F8),
      showNewAppBarTitle: true,
      showDropDown: false,
      dropdownIndexValue: _currentPage,
      dropDownIndexChange: (index) {
        setState(() {
          _currentPage = index!;
        });
      },
      dropDownList: [
        // TranslationBase.of(context).booked,
        TranslationBase.of(context).upcoming,
        TranslationBase.of(context).arrived,
      ],
      description: TranslationBase.of(context).infoMyAppointments,
      body: Container(
        child: Column(children: [
          Row(
            children: [
              MyTabView(TranslationBase.of(context).byClinic, FilterType.Clinic, filterType!, () {
                setFilterType(FilterType.Clinic);
              }),
              MyTabView(TranslationBase.of(context).byHospital, FilterType.Hospital, filterType!, () {
                setFilterType(FilterType.Hospital);
              }),
            ],
          ),
          SizedBox(height: 20),
          Padding(
            padding: EdgeInsets.only(left: 21, right: 21),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                myRadioButton(TranslationBase.of(context).upcoming, 1),
                // myRadioButton(TranslationBase.of(context).upcoming, 1),
                myRadioButton(TranslationBase.of(context).arrived, 2),
              ],
            ),
          ),
          isDataLoaded
              ? Expanded(
                  child: IndexedStack(
                    index: _currentPage,
                    children: [getBookedAppointments(), getBookedAndConfirmedAppointments(), getArrivedAppointments()],
                  ),
                )
              : Container(),
        ]),
      ),
    );
  }

  getPatientAppointmentHistory(bool isForUpcoming, bool isForArrived) {
    int? languageID = projectViewModel!.isArabic ? 1 : 2;
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();

    upcomingAppoList.clear();
    arrivedAppoListNew.clear();

    bookedAppoList.clear();
    confirmedAppoList.clear();
    arrivedAppoList.clear();

    _patientBookedAppointmentListHospital.clear();
    _patientConfirmedAppointmentListHospital.clear();
    _patientArrivedAppointmentListHospital.clear();

    _patientBookedAppointmentListClinic.clear();
    _patientConfirmedAppointmentListClinic.clear();
    _patientArrivedAppointmentListClinic.clear();

    _patientBookedAndConfirmedAppointmentListHospital.clear();
    _patientBookedAndConfirmedAppointmentListClinic.clear();

    service.getPatientAppointmentHistory(false, languageID, context, isForUpcomming: isForUpcoming, IsForArrived: isForArrived).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      setState(() {
        if (res['MessageStatus'] == 1) {
          if (res['AppoimentAllHistoryResultList'].length != 0) {
            res['AppoimentAllHistoryResultList'].forEach((v) {
              if (isForArrived) {
                arrivedAppoListNew.add(new AppoitmentAllHistoryResultList.fromJson(v));
              } else {
                upcomingAppoList.add(new AppoitmentAllHistoryResultList.fromJson(v));
              }
            });
            sortAppointmentList(isForUpcoming, isForArrived);
          } else {}
        } else {
          AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
        }
        isDataLoaded = true;
      });
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err);
    });
    getToDoCount();
  }

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

  bool isConfirmed(AppoitmentAllHistoryResultList appo) {
    return AppointmentType.isConfirmed(appo);
  }

  bool isArrived(AppoitmentAllHistoryResultList appo) {
    return AppointmentType.isArrived(appo);
  }

  bool isBooked(AppoitmentAllHistoryResultList appo) {
    return AppointmentType.isBooked(appo);
  }

  sortAppointmentList(bool isForUpcoming, bool isForArrived) {
    if (isForArrived) {
      arrivedAppoListNew.forEach((v) {
        if (isBooked(v)) {
          bookedAppoList.add(v);
        }

        if (isConfirmed(v)) {
          confirmedAppoList.add(v);
        }

        if (isArrived(v)) {
          arrivedAppoList.add(v);
        }
      });
    } else {
      upcomingAppoList.forEach((v) {
        if (isBooked(v)) {
          bookedAppoList.add(v);
        }

        if (isConfirmed(v)) {
          confirmedAppoList.add(v);
        }

        if (isArrived(v)) {
          arrivedAppoList.add(v);
        }
      });
    }

    bookedAppoList.forEach((element) {
      List<PatientAppointmentList> doctorByClinic = _patientBookedAppointmentListClinic
          .where(
            (elementClinic) => elementClinic.filterName == element.clinicName,
          )
          .toList();

      if (doctorByClinic.length != 0) {
        _patientBookedAppointmentListClinic[_patientBookedAppointmentListClinic.indexOf(doctorByClinic[0])].patientDoctorAppointmentList!.add(element);
      } else {
        _patientBookedAppointmentListClinic.add(PatientAppointmentList(filterName: element.clinicName, patientDoctorAppointment: element));
      }

      List<PatientAppointmentList> doctorByHospital = _patientBookedAppointmentListHospital
          .where(
            (elementClinic) => elementClinic.filterName == element.projectName,
          )
          .toList();

      if (doctorByHospital.length != 0) {
        _patientBookedAppointmentListHospital[_patientBookedAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList!.add(element);
      } else {
        _patientBookedAppointmentListHospital.add(PatientAppointmentList(filterName: element.projectName, patientDoctorAppointment: element));
      }
    });

    confirmedAppoList.forEach((element) {
      List<PatientAppointmentList> doctorByClinic = _patientConfirmedAppointmentListClinic
          .where(
            (elementClinic) => elementClinic.filterName == element.clinicName,
          )
          .toList();

      if (doctorByClinic.length != 0) {
        _patientConfirmedAppointmentListClinic[_patientConfirmedAppointmentListClinic.indexOf(doctorByClinic[0])].patientDoctorAppointmentList!.add(element);
      } else {
        _patientConfirmedAppointmentListClinic.add(PatientAppointmentList(filterName: element.clinicName, patientDoctorAppointment: element));
      }

      List<PatientAppointmentList> doctorByHospital = _patientConfirmedAppointmentListHospital
          .where(
            (elementClinic) => elementClinic.filterName == element.projectName,
          )
          .toList();

      if (doctorByHospital.length != 0) {
        _patientConfirmedAppointmentListHospital[_patientConfirmedAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList!.add(element);
      } else {
        _patientConfirmedAppointmentListHospital.add(PatientAppointmentList(filterName: element.projectName, patientDoctorAppointment: element));
      }

      //Merging Booked & Confirmed Appointments into Upcoming Tab
      // _patientBookedAndConfirmedAppointmentListHospital.addAll(_patientConfirmedAppointmentListHospital);
      // _patientBookedAndConfirmedAppointmentListClinic.addAll(_patientConfirmedAppointmentListClinic);
    });

    arrivedAppoList.forEach((element) {
      List<PatientAppointmentList> doctorByClinic = _patientArrivedAppointmentListClinic
          .where(
            (elementClinic) => elementClinic.filterName == element.clinicName,
          )
          .toList();

      if (doctorByClinic.length != 0) {
        _patientArrivedAppointmentListClinic[_patientArrivedAppointmentListClinic.indexOf(doctorByClinic[0])].patientDoctorAppointmentList!.add(element);
      } else {
        _patientArrivedAppointmentListClinic.add(PatientAppointmentList(filterName: element.clinicName, patientDoctorAppointment: element));
      }

      List<PatientAppointmentList> doctorByHospital = _patientArrivedAppointmentListHospital
          .where(
            (elementClinic) => elementClinic.filterName == element.projectName,
          )
          .toList();

      if (doctorByHospital.length != 0) {
        _patientArrivedAppointmentListHospital[_patientArrivedAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList!.add(element);
      } else {
        _patientArrivedAppointmentListHospital.add(PatientAppointmentList(filterName: element.projectName, patientDoctorAppointment: element));
      }

      // openAppointmentsTab();
    });

    //Merging Booked & Confirmed Appointments into Upcoming Tab
    _patientBookedAndConfirmedAppointmentListHospital.addAll(_patientBookedAppointmentListHospital);
    _patientBookedAndConfirmedAppointmentListClinic.addAll(_patientBookedAppointmentListClinic);

    _patientBookedAndConfirmedAppointmentListHospital.addAll(_patientConfirmedAppointmentListHospital);
    _patientBookedAndConfirmedAppointmentListClinic.addAll(_patientConfirmedAppointmentListClinic);

  }

  openAppointmentsTab() async {
    var flag = await this.sharedPref.getInt(IS_SEARCH_APPO);
    int? index;
    if (flag == 1) {
      index = 0;
    } else if (flag == 2) {
      index = 1;
    } else if (flag == 3) {
      index = 2;
    } else {
      if (_patientBookedAppointmentListClinic.length != 0) {
        index = 0;
      } else if (_patientConfirmedAppointmentListClinic.length != 0) {
        index = 1;
      } else if (_patientArrivedAppointmentListClinic.length != 0) {
        index = 2;
        //   return;
      }
    }

    _currentPage = index!;
  }

  Widget getBookedAppointments() {
    // return _getAppointment(bookedAppoList.length, (filterType == FilterType.Clinic) ? _patientBookedAppointmentListClinic : _patientBookedAppointmentListHospital);
    return Container();
  }

  Widget getBookedAndConfirmedAppointments() {
    return _getAppointment(
        (bookedAppoList.length + confirmedAppoList.length), (filterType == FilterType.Clinic) ? _patientBookedAndConfirmedAppointmentListClinic : _patientBookedAndConfirmedAppointmentListHospital);
  }

  Widget _getAppointment(int _listLength, List<PatientAppointmentList> _list) {
    return Container(
      child: Container(
        child: _listLength != 0
            ? _appointmentExpandableList(_list)
            : Container(
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Image.asset("assets/images/new-design/noAppointmentIcon.png"),
                      Container(
                        margin: EdgeInsets.only(top: 10.0),
                        child: Text(
                          _currentPage == 0
                              ? TranslationBase.of(context).noBookedAppo
                              : (_currentPage == 1 ? TranslationBase.of(context).noUpcomingAppointment : TranslationBase.of(context).noArrivedAppo),
                          style: TextStyle(
                            fontSize: 16.0,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }

  Widget _appointmentExpandableList(List<PatientAppointmentList> _patientAppointmentList) {
    return ListView.separated(
      addAutomaticKeepAlives: true,
      physics: BouncingScrollPhysics(),
      padding: EdgeInsets.only(top: 12),
      separatorBuilder: (context, index) {
        return Container(
          height: 12,
          margin: EdgeInsets.only(left: 21, right: 21),
          // color: Color(0xffD9D9D9),
        );
      },
      itemBuilder: (context, index) {
        List<AppoitmentAllHistoryResultList> _appointmentAllHistoryResultList = _patientAppointmentList[index].patientDoctorAppointmentList!;
        return AppExpandableNotifier(
          title: _patientAppointmentList[index].filterName,
          bodyWidget: ListView.separated(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.only(bottom: 14, top: 14, left: 21, right: 21),
              itemBuilder: (context, _index) {
                AppoitmentAllHistoryResultList _appointmentResult = _appointmentAllHistoryResultList[_index];
                bool _isSortByClinic = filterType == FilterType.Clinic;

                return DoctorCard(
                    onTap: () => Navigator.push(
                          context,
                          FadePage(
                            page: AppointmentDetails(
                              appo: _appointmentResult,
                              // parentIndex: _currentPage,
                              parentIndex: _appointmentResult.patientStatusType == 42 ? 1 : 0,
                            ),
                          ),
                        ).then((value) {
                          if (_currentPage == 1) {
                            getPatientAppointmentHistory(true, false);
                          }
                          if (_currentPage == 2) {
                            getPatientAppointmentHistory(false, true);
                          }
                        }),
                    isInOutPatient: _appointmentResult.isInOutPatient,
                    name: _appointmentResult.doctorTitle! + " " + _appointmentResult.doctorNameObj!,
                    projectID: _appointmentResult.projectID!,
                    //    billNo: _appointmentResult.invoiceNo,
                    profileUrl: _appointmentResult.doctorImageURL,
                    subName: _isSortByClinic ? _appointmentResult.projectName : _appointmentResult.clinicName,
                    isLiveCareAppointment: _appointmentResult.isLiveCareAppointment,
                    date: DateUtil.convertStringToDate(_appointmentResult.appointmentDate!),
                    isSortByClinic: _isSortByClinic,
                    rating: _appointmentResult.actualDoctorRate + 0.0,
                    appointmentTime: _appointmentResult.isLiveCareAppointment!
                        ? DateUtil.convertStringToDate(_appointmentResult.appointmentDate).toString().split(" ")[1].substring(0, 5)
                        : _appointmentResult.startTime!.substring(0, 5),
                    // appointmentTime: _appointmentResult.startTime.substring(0, 5),
                    remainingTimeInMinutes: (_appointmentResult.patientStatusType == AppointmentType.BOOKED || _appointmentResult.patientStatusType == AppointmentType.CONFIRMED)
                        ? _appointmentResult.remaniningHoursTocanPay
                        : null

                    //projectViewModel.isArabic ? DateUtil.getMonthDayYearDateFormattedAr(labOrder.orderDate) : DateUtil.getMonthDayYearDateFormatted(labOrder.orderDate),
                    );
              },
              separatorBuilder: (context, index) => SizedBox(height: 14),
              itemCount: _appointmentAllHistoryResultList.length),
        );
      },
      itemCount: _patientAppointmentList.length,
    );
  }

  Widget getConfirmedAppointments() {
    return _getAppointment(confirmedAppoList.length, (filterType == FilterType.Clinic) ? _patientConfirmedAppointmentListClinic : _patientConfirmedAppointmentListHospital);
  }

  Widget getArrivedAppointments() {
    return _getAppointment(arrivedAppoList.length, (filterType == FilterType.Clinic) ? _patientArrivedAppointmentListClinic : _patientArrivedAppointmentListHospital);
  }

  setFilterType(FilterType filterType) {
    setState(() {
      this.filterType = filterType;
    });
  }

  Widget myRadioButton(String _label, int _value) {
    return InkWell(
      onTap: () {
        setState(() {
          _currentPage = _value;
          if (_value == 1) {
            getPatientAppointmentHistory(true, false);
          }
          if (_value == 2) {
            getPatientAppointmentHistory(false, true);
          }
        });
      },
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 22,
            height: 22,
            child: Radio(
              value: _value,
              activeColor: _value == _currentPage ? Color(0xffD02127) : Color(0xffE8E8E8),
              groupValue: _currentPage,
              onChanged: (index) {
                setState(() {
                  _currentPage = index!;
                  if (_value == 1) {
                    getPatientAppointmentHistory(true, false);
                  }
                  if (_value == 2) {
                    getPatientAppointmentHistory(false, true);
                  }
                });
              },
            ),
          ),
          SizedBox(width: 10),
          Text(
            _label,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Color(0xff575757),
              letterSpacing: -0.56,
            ),
          ),
        ],
      ),
    );
  }
}
