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/pages/MyAppointments/widgets/AppointmentCardView.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/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/others/app_expandable_notifier.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.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 {
  TabController _tabController;

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

  List<ImagesInfo> imagesInfo = List();

  FilterType filterType;

  @override
  void initState() {
    _tabController = new TabController(length: 3, vsync: this);
    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
  Widget build(BuildContext context) {
    return AppScaffold(
      appBarTitle: TranslationBase.of(context).myAppointments,
      isShowAppBar: true,
      imagesInfo: imagesInfo,
      description: TranslationBase.of(context).infoMyAppointments,
      body: Container(
        child: Column(children: [
          TabBar(
            tabs: [
              Tab(
                  child: Text(TranslationBase.of(context).booked,
                      style: TextStyle(color: Colors.black))),
              Tab(
                child: Text(TranslationBase.of(context).confirmed,
                    style: TextStyle(color: Colors.black)),
              ),
              Tab(
                child: Text(TranslationBase.of(context).arrived,
                    style: TextStyle(color: Colors.black)),
              )
            ],
            controller: _tabController,
          ),
          Divider(
            color: Colors.grey[600],
            thickness: 0.5,
          ),
          Row(
            children: <Widget>[
              Expanded(
                flex: 1,
                child: InkWell(
                  onTap: () => setFilterType(FilterType.Clinic),
                  child: ListTile(
                    title: Text(TranslationBase.of(context).clinic),
                    leading: Radio(
                      value: FilterType.Clinic,
                      groupValue: filterType,
                      activeColor: Color(0xffB8382C),
                      onChanged: (FilterType value) {
                        setFilterType(value);
                      },
                    ),
                  ),
                ),
              ),
              Expanded(
                flex: 1,
                child: InkWell(
                  onTap: () => setFilterType(FilterType.Hospital),
                  child: ListTile(
                    title: Text(TranslationBase.of(context).hospital),
                    leading: Radio(
                      value: FilterType.Hospital,
                      groupValue: filterType,
                      activeColor: Color(0xffB8382C),
                      onChanged: (FilterType value) => setFilterType(value),
                    ),
                  ),
                ),
              )
            ],
          ),
          isDataLoaded
              ? Expanded(
                  child: new TabBarView(
                    physics: NeverScrollableScrollPhysics(),
                    children: [
                      getBookedAppointments(),
                      getConfirmedAppointments(),
                      getArrivedAppointments()
                    ],
                    controller: _tabController,
                  ),
                )
              : 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) {
      print(res['AppoimentAllHistoryResultList'].length);
      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);
      Navigator.of(context).pop();
    });
  }

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

    if (flag == 1) {
      _tabController.index = 0;
    } else if (flag == 2) {
      _tabController.index = 1;
    } else if (flag == 3) {
      _tabController.index = 2;
    } else {
      if (widget._patientBookedAppointmentListClinic.length != 0) {
        _tabController.index = 0;
      } else if (widget._patientConfirmedAppointmentListClinic.length != 0) {
        _tabController.index = 1;
      } else if (widget._patientArrivedAppointmentListClinic.length != 0) {
        _tabController.index = 2;
        return;
      }
    }
  }

  Widget getBookedAppointments() {
    return Container(
      child: Container(
        child: widget.bookedAppoList.length != 0
            ? SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                child: Column(
                  children: <Widget>[
                    ...List.generate(
                      filterType == FilterType.Clinic
                          ? widget._patientBookedAppointmentListClinic.length
                          : widget._patientBookedAppointmentListHospital.length,
                      (index) => AppExpandableNotifier(
                          title: filterType == FilterType.Clinic
                              ? widget
                                  ._patientBookedAppointmentListClinic[index]
                                  .filterName
                              : widget
                                  ._patientBookedAppointmentListHospital[index]
                                  .filterName,
                          bodyWidget: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: filterType == FilterType.Clinic
                                ? widget
                                    ._patientBookedAppointmentListClinic[index]
                                    .patientDoctorAppointmentList
                                    .map((doctor) {
                                    return AppointmentCard(
                                      appo: doctor,
                                      onReloadAppointmentHistory:
                                          getPatientAppointmentHistory,
                                    );
                                  }).toList()
                                : widget
                                    ._patientBookedAppointmentListHospital[
                                        index]
                                    .patientDoctorAppointmentList
                                    .map((doctor) {
                                    return AppointmentCard(
                                      appo: doctor,
                                      onReloadAppointmentHistory:
                                          getPatientAppointmentHistory,
                                    );
                                  }).toList(),
                          )),
                    )
                  ],
                ),
              )
            : 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(TranslationBase.of(context).noBookedAppo,
                            style: TextStyle(
                              fontSize: 16.0,
                            )),
                      ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }

  Widget getConfirmedAppointments() {
    return widget.confirmedAppoList.length != 0
        ? Container(
            margin: EdgeInsets.only(top: 10.0),
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: Column(
                children: <Widget>[
                  ...List.generate(
                    filterType == FilterType.Clinic
                        ? widget._patientConfirmedAppointmentListClinic.length
                        : widget
                            ._patientConfirmedAppointmentListHospital.length,
                    (index) => AppExpandableNotifier(
                        title: filterType == FilterType.Clinic
                            ? widget
                                ._patientConfirmedAppointmentListClinic[index]
                                .filterName
                            : widget
                                ._patientConfirmedAppointmentListHospital[index]
                                .filterName,
                        bodyWidget: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: filterType == FilterType.Clinic
                              ? widget
                                  ._patientConfirmedAppointmentListClinic[index]
                                  .patientDoctorAppointmentList
                                  .map((doctor) {
                                  return AppointmentCard(
                                    appo: doctor,
                                    onReloadAppointmentHistory:
                                        getPatientAppointmentHistory,
                                  );
                                }).toList()
                              : widget
                                  ._patientConfirmedAppointmentListHospital[
                                      index]
                                  .patientDoctorAppointmentList
                                  .map((doctor) {
                                  return AppointmentCard(
                                    appo: doctor,
                                    onReloadAppointmentHistory:
                                        getPatientAppointmentHistory,
                                  );
                                }).toList(),
                        )),
                  )
                ],
              ),
            ),
          )
        : 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(TranslationBase.of(context).noConfirmedAppo,
                        style: TextStyle(
                          fontSize: 16.0,
                        )),
                  ),
                ],
              ),
            ),
          );
  }

  Widget getArrivedAppointments() {
    return widget.arrivedAppoList.length != 0
        ? Container(
            margin: EdgeInsets.only(top: 10.0),
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: Column(
                children: <Widget>[
                  ...List.generate(
                    filterType == FilterType.Clinic
                        ? widget._patientArrivedAppointmentListClinic.length
                        : widget._patientArrivedAppointmentListHospital.length,
                    (index) => AppExpandableNotifier(
                      title: filterType == FilterType.Clinic
                          ? widget._patientArrivedAppointmentListClinic[index]
                              .filterName
                          : widget._patientArrivedAppointmentListHospital[index]
                              .filterName,
                      bodyWidget: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: filterType == FilterType.Clinic
                            ? widget._patientArrivedAppointmentListClinic[index]
                                .patientDoctorAppointmentList
                                .map((doctor) {
                                return AppointmentCard(
                                  appo: doctor,
                                  onReloadAppointmentHistory:
                                      getPatientAppointmentHistory,
                                );
                              }).toList()
                            : widget
                                ._patientArrivedAppointmentListHospital[index]
                                .patientDoctorAppointmentList
                                .map((doctor) {
                                return AppointmentCard(
                                  appo: doctor,
                                  onReloadAppointmentHistory:
                                      getPatientAppointmentHistory,
                                );
                              }).toList(),
                      ),
                    ),
                  )
                ],
              ),
            ),
          )
        : 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(TranslationBase.of(context).noArrivedAppo,
                        style: TextStyle(
                          fontSize: 16.0,
                        )),
                  ),
                ],
              ),
            ),
          );
  }

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