import 'package:diplomaticquarterapp/config/shared_pref_kay.dart';
import 'package:diplomaticquarterapp/core/enum/filter_type.dart';
import 'package:diplomaticquarterapp/core/model/ImagesInfo.dart';
import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/models/Appointments/AppoimentAllHistoryResultList.dart';
import 'package:diplomaticquarterapp/pages/MyAppointments/models/AppointmentType.dart';
import 'package:diplomaticquarterapp/services/appointment_services/GetDoctorsList.dart';
import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/data_display/medical/doctor_card.dart';
import 'package:diplomaticquarterapp/widgets/new_design/my_tab_view.dart';
import 'package:diplomaticquarterapp/widgets/others/app_expandable_notifier.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'AppointmentDetails.dart';

class MyAppointments extends StatefulWidget {
  List<AppoitmentAllHistoryResultList> appoList = [];

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

  List<PatientAppointmentList> _patientBookedAppointmentListHospital = List();
  List<PatientAppointmentList> _patientConfirmedAppointmentListHospital = List();
  List<PatientAppointmentList> _patientArrivedAppointmentListHospital = List();

  List<PatientAppointmentList> _patientBookedAppointmentListClinic = List();
  List<PatientAppointmentList> _patientConfirmedAppointmentListClinic = List();
  List<PatientAppointmentList> _patientArrivedAppointmentListClinic = List();

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

class _MyAppointmentsState extends State<MyAppointments> with SingleTickerProviderStateMixin {
  bool isDataLoaded = false;
  var sharedPref = new AppSharedPreferences();
  AuthenticatedUserObject authenticatedUserObject = locator<AuthenticatedUserObject>();

  List<ImagesInfo> imagesInfo = List();

  FilterType filterType;

  int _currentPage = 0;

  @override
  void initState() {
    filterType = FilterType.Clinic;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (Provider.of<ProjectViewModel>(context, listen: false).isLogin) getPatientAppointmentHistory();
    });
    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) {
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).myAppointmentsList,
      isShowAppBar: true,
      imagesInfo: imagesInfo,
      showNewAppBar: true,
      backgroundColor: Color(0xffF8F8F8),
      showNewAppBarTitle: true,
      showDropDown: true,
      dropdownIndexValue: _currentPage,
      dropDownIndexChange: (index) {
        setState(() {
          _currentPage = index;
        });
      },
      dropDownList: [
        TranslationBase.of(context).booked,
        TranslationBase.of(context).confirmed,
        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.spaceBetween,
              children: [
                myRadioButton(TranslationBase.of(context).booked, 0),
                myRadioButton(TranslationBase.of(context).confirmed, 1),
                myRadioButton(TranslationBase.of(context).arrived, 2),
              ],
            ),
          ),
          isDataLoaded
              ? Expanded(
                  child: IndexedStack(
                    index: _currentPage,
                    children: [getBookedAppointments(), getConfirmedAppointments(), getArrivedAppointments()],
                  ),
                )
              : Container(),
        ]),
      ),
    );
  }

  getPatientAppointmentHistory() {
    GifLoaderDialogUtils.showMyDialog(context);
    DoctorsListService service = new DoctorsListService();
    widget.appoList.clear();
    widget.bookedAppoList.clear();
    widget.confirmedAppoList.clear();
    widget.arrivedAppoList.clear();

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

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

    service.getPatientAppointmentHistory(false, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      setState(() {
        if (res['MessageStatus'] == 1) {
          // setState(() {
          if (res['AppoimentAllHistoryResultList'].length != 0) {
            // isDataLoaded = true;
            res['AppoimentAllHistoryResultList'].forEach((v) {
              widget.appoList.add(new AppoitmentAllHistoryResultList.fromJson(v));
            });
            sortAppointmentList();
          } else {}
          // });
        } else {
          AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
        }
        isDataLoaded = true;
      });
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: 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() {
    widget.appoList.forEach((v) {
      if (isBooked(v)) {
        widget.bookedAppoList.add(v);
      }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      openAppointmentsTab();
    });
  }

  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 (widget._patientBookedAppointmentListClinic.length != 0) {
        index = 0;
      } else if (widget._patientConfirmedAppointmentListClinic.length != 0) {
        index = 1;
      } else if (widget._patientArrivedAppointmentListClinic.length != 0) {
        index = 2;
        //   return;
      }
    }

    _currentPage = index;
  }

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

  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).noConfirmedAppo : TranslationBase.of(context).noArrivedAppo),
                          style: TextStyle(
                            fontSize: 16.0,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }

  Widget _appointmentExpandableList(List<PatientAppointmentList> _patientAppointmentList) {
    return ListView.separated(
      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,
                            ),
                          ),
                        ).then((value) {
                          getPatientAppointmentHistory();
                        }),
                    isInOutPatient: _appointmentResult.isInOutPatient,
                    name: _appointmentResult.doctorTitle + " " + _appointmentResult.doctorNameObj,
                    //    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(widget.confirmedAppoList.length, (filterType == FilterType.Clinic) ? widget._patientConfirmedAppointmentListClinic : widget._patientConfirmedAppointmentListHospital);
  }

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

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

  Widget myRadioButton(String _label, int _value) {
    return InkWell(
      onTap: () {
        setState(() {
          _currentPage = _value;
        });
      },
      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;
                });
                //_pageController.animateToPage(index, duration: Duration(milliseconds: 250), curve: Curves.easeInOut);
              },
            ),
          ),
          SizedBox(width: 10),
          Text(
            _label,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: Color(0xff575757),
              letterSpacing: -0.56,
            ),
          ),
        ],
      ),
    );
  }
}
