import 'dart:collection';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/pages/BookAppointment/components/LaserClinic.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../config/shared_pref_kay.dart';
import '../../../config/size_config.dart';
import '../../../core/model/hospitals/hospitals_model.dart';
import '../../../core/viewModels/project_view_model.dart';
import '../../../models/Appointments/DoctorListResponse.dart';
import '../../../models/Appointments/SearchInfoModel.dart';
import '../../../models/Clinics/ClinicListResponse.dart';
import '../../../services/appointment_services/GetDoctorsList.dart';
import '../../../services/authentication/auth_provider.dart';
import '../../../services/clinic_services/get_clinic_service.dart';
import '../../../uitl/app_toast.dart';
import '../../../uitl/gif_loader_dialog_utils.dart';
import '../../../uitl/translations_delegate_base.dart';
import '../../../widgets/transitions/fade_page.dart';
import '../../livecare/livecare_home.dart';
import '../DentalComplaints.dart';
import '../LaserBooking.dart';
import '../SearchResults.dart';
import '../dialog/clinic_list_dialog.dart';
import 'LiveCareBookAppointment.dart';

class SearchByHospital extends StatefulWidget {
  @override
  State<SearchByHospital> createState() => _SearchByHospitalState();
}

class _SearchByHospitalState extends State<SearchByHospital> {
  HospitalsModel? selectedHospital;
  bool nearestAppo = false;

  String? selectedClinicName;
  List<HospitalsModel> projectsList = [];
  List<ListClinicCentralized>? clinicIds = List.empty();

  final GlobalKey projectDropdownKey = GlobalKey();

  List<ListClinicCentralized> clinicsList = [];
  bool isMobileAppDentalAllow = false;
  ListClinicCentralized? selectedClinic;

  String? dropdownValue;
  String dropdownTitle = "";

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) => getProjectsList());
  }

  @override
  Widget build(BuildContext context) {
    AppGlobal.context = context;

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 6, right: 6, top: 16),
          child: Row(
            children: <Widget>[
              Checkbox(
                activeColor: CustomColors.accentColor,
                value: nearestAppo,
                onChanged: (bool? value) {
                  nearestAppo = value ?? false;
                  setState(() {});
                },
              ),
              AutoSizeText(
                TranslationBase.of(context).nearestAppo.trim(),
                maxLines: 1,
                minFontSize: 10,
                style: TextStyle(
                  fontSize: SizeConfig.textMultiplier! * 1.4,
                  fontWeight: FontWeight.w600,
                  letterSpacing: -0.39,
                  height: 0.8,
                ),
              ),
              // Text(TranslationBase.of(context).nearestAppo, style: TextStyle(fontSize: 14.0, letterSpacing: -0.56)),
            ],
          ),
        ),
        mHeight(8),
        InkWell(
          onTap: () {
            openDropdown(projectDropdownKey);
          },
          child: Container(
              width: double.infinity,
              decoration: containerRadius(Colors.white, 12),
              margin: EdgeInsets.only(left: 20, right: 20),
              padding: EdgeInsets.only(left: 10, right: 10, top: 12, bottom: 12),
              child: Row(
                children: [
                  Flexible(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          TranslationBase.of(context).selectHospital,
                          style: TextStyle(
                            fontSize: 11,
                            letterSpacing: -0.44,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        Container(
                          height: 18,
                          width: double.infinity,
                          child: DropdownButtonHideUnderline(
                            child: DropdownButton<HospitalsModel>(
                              key: projectDropdownKey,
                              hint: Text(TranslationBase.of(context).selectHospital),
                              value: selectedHospital,
                              iconSize: 0,
                              isExpanded: true,
                              style: TextStyle(fontSize: 14, letterSpacing: -0.56, color: Colors.black),
                              items: projectsList.map((HospitalsModel item) {
                                return DropdownMenuItem<HospitalsModel>(
                                  value: item,
                                  child: AutoSizeText(
                                    item.name!,
                                    maxLines: 1,
                                    minFontSize: 10,
                                    style: TextStyle(
                                      fontSize: SizeConfig.textMultiplier! * 1.6,
                                      fontWeight: FontWeight.w600,
                                      letterSpacing: -0.39,
                                      height: 0.8,
                                    ),
                                  ),
                                  // Text('${item.name!}'),
                                );
                              }).toList(),
                              onChanged: (HospitalsModel? newValue) {
                                getClinicWrtHospital(newValue);
                                setState(() {
                                  selectedHospital = newValue;
                                });
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Icon(Icons.keyboard_arrow_down),
                ],
              )),
        ),
        if (clinicIds?.isNotEmpty == true) ...[
          mHeight(8),
          InkWell(
            onTap: () {
              showClickListDialog(context, clinicIds ?? List.empty(), onSelection: (ListClinicCentralized clincs) {
                selectedClinic = clincs;
                Navigator.pop(context);
                setState(() {
                  dropdownTitle = clincs.clinicDescription!;
                  dropdownValue = clincs.clinicID.toString() + "-" + clincs.isLiveCareClinicAndOnline.toString() + "-" + clincs.liveCareClinicID.toString() + "-" + clincs.liveCareServiceID.toString();
                });
                getDoctorsList(context);

                context.read<ProjectViewModel>().analytics.appointment.book_appointment_select_clinic(appointment_type: 'regular', clinic: clincs.clinicDescription);
              });
            },
            child: Container(
              width: double.infinity,
              decoration: containerRadius(Colors.white, 12),
              margin: EdgeInsets.only(left: 20, right: 20),
              padding: EdgeInsets.only(left: 10, right: 10, top: 12, bottom: 8),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          TranslationBase.of(context).selectClinic,
                          style: TextStyle(
                            fontSize: 11,
                            letterSpacing: -0.44,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(top: 4, bottom: 2),
                          child: Text(
                            dropdownTitle,
                            style: TextStyle(
                              fontSize: 13,
                              letterSpacing: -0.44,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Icon(Icons.keyboard_arrow_down),
                ],
              ),
            ),
          )
        ]
      ],
    );
  }

  void openDropdown(GlobalKey key) {
    GestureDetector? detector;

    void searchForGestureDetector(BuildContext element) {
      element.visitChildElements((element) {
        if (element.widget != null && element.widget is GestureDetector) {
          detector = element.widget as GestureDetector?;
          //return false;
        } else {
          searchForGestureDetector(element);
        }

        //return true;
      });
    }

    searchForGestureDetector(key.currentContext!);
    assert(detector != null);

    detector!.onTap!();
  }

  GestureDetector? searchForGestureDetector(BuildContext element) {
    GestureDetector? detector;
    element.visitChildElements((element) {
      if (element.widget != null && element.widget is GestureDetector) {
        detector = element.widget as GestureDetector?;
        //return false;
      } else {
        searchForGestureDetector(element);
      }
    });
    return detector;
  }

  getProjectsList() {
    GifLoaderDialogUtils.showMyDialog(context);

    int languageID = context.read<ProjectViewModel>().isArabic ? 1 : 2;
    ClinicListService service = new ClinicListService();
    List<HospitalsModel> projectsListLocal = [];
    service.getProjectsList(languageID, context).then((res) {
      GifLoaderDialogUtils.hideDialog(context);

      if (res['MessageStatus'] == 1) {
        setState(() {
          res['ListProject'].forEach((v) {
            projectsListLocal.add(new HospitalsModel.fromJson(v));
          });
          projectsList = projectsListLocal;
        });
      } else {}
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);

      print(err);
    });
  }

  void getClinicWrtHospital(HospitalsModel? newValue) async {
    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService service = new ClinicListService();
    List<HospitalsModel> projectsListLocal = [];
    setState(() {
      clinicIds = List.empty();
    });
    List<ListClinicCentralized> clinicId = [];
    try {
      Map res = await service.getClinicByHospital(projectID: newValue?.mainProjectID.toString() ?? "");
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        List list = res['ListClinic'];

        if (list.isEmpty) {
          AppToast.showErrorToast(
            message: TranslationBase.of(context).NoClinicFound,
          );
        }
        res['ListClinic'].forEach((v) {
          clinicId.add(ListClinicCentralized.fromJson(v));
        });
        clinicIds = clinicId;
        setState(() {});
      } else {
        AppToast.showErrorToast(
          message: TranslationBase.of(context).NoClinicFound,
        );
      }
    } catch (e) {
      print("the error is $e");
      AppToast.showErrorToast(
        message: TranslationBase.of(context).NoClinicFound,
      );
      GifLoaderDialogUtils.hideDialog(context);
    }

    // .then((res) {
    // print("the result is obtained");
    // GifLoaderDialogUtils.hideDialog(context);
    // if (res['MessageStatus'] == 1) {
    // List list = res['ListClinic'];
    //
    // if(list.isEmpty){
    // AppToast.showErrorToast(message:
    // TranslationBase.of(context).NoClinicFound,
    // );
    //
    // }
    // res['ListClinic'].forEach((v) {
    // clinicId?.add(ListClinicCentralized.fromJson(v));
    // });
    // clinicIds = clinicId;
    // setState(() {
    //
    // });
    // } else {
    // AppToast.showErrorToast(message:
    // TranslationBase.of(context).NoClinicFound,
    // );
    // }
    // }).catchError((err) {
    // print('the  error is $err');
    // AppToast.showErrorToast(message:
    // TranslationBase.of(context).NoClinicFound,
    // );
    // GifLoaderDialogUtils.hideDialog(context);
    // }).catchError((err) {
    // AppToast.showErrorToast(message:
    // TranslationBase.of(context).NoClinicFound,
    // );
    // GifLoaderDialogUtils.hideDialog(context);
    //
    // print(err);
    // });
  }

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

  Future navigateToDentalComplaints(BuildContext context, SearchInfo searchInfo) async {
    Navigator.push(
      context,
      FadePage(
        page: DentalComplaints(searchInfo: searchInfo),
      ),
    ).then((value) {
      setState(() {
        dropdownValue = null;
        selectedHospital = null;
        dropdownTitle = "";
        clinicIds = List.empty();
      });
    });
  }

  callDoctorsSearchAPI(int clinicID) {
    int languageID = context.read<ProjectViewModel>().isArabic ? 1 : 2;
    GifLoaderDialogUtils.showMyDialog(context);
    List<DoctorList> doctorsList = [];
    List<String> arr = [];
    List<String> arrDistance = [];
    List<String> result;
    int numAll;
    List<PatientDoctorAppointmentList> _patientDoctorAppointmentListHospital = [];

    DoctorsListService service = new DoctorsListService();
    service.getDoctorsList(clinicID, selectedHospital?.mainProjectID.toString() != "" ? int.parse(selectedHospital?.mainProjectID.toString() ?? "-1") : 0, nearestAppo, languageID, null).then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        setState(() {
          if (res['DoctorList'].length != 0) {
            doctorsList.clear();
            res['DoctorList'].forEach((v) {
              doctorsList.add(DoctorList.fromJson(v));
            });
            doctorsList.forEach((element) {
              List<PatientDoctorAppointmentList> doctorByHospital = _patientDoctorAppointmentListHospital
                  .where(
                    (elementClinic) => elementClinic.filterName == element.getProjectCompleteName(),
                  )
                  .toList();

              if (doctorByHospital.length != 0) {
                _patientDoctorAppointmentListHospital[_patientDoctorAppointmentListHospital.indexOf(doctorByHospital[0])].patientDoctorAppointmentList!.add(element);
              } else {
                _patientDoctorAppointmentListHospital
                    .add(PatientDoctorAppointmentList(filterName: element.getProjectCompleteName(), distanceInKMs: element.projectDistanceInKiloMeters.toString(), patientDoctorAppointment: element));
              }
            });
          } else {}
        });

        result = LinkedHashSet<String>.from(arr).toList();
        numAll = result.length;
        navigateToSearchResults(context, doctorsList, _patientDoctorAppointmentListHospital);
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err, localContext: context);
    });
  }

  Future navigateToSearchResults(context, List<DoctorList> docList, List<PatientDoctorAppointmentList> patientDoctorAppointmentListHospital) async {
    Navigator.push(context,
            FadePage(page: SearchResults(isLiveCareAppointment: false, doctorsList: docList, isDoctorSearchResult: false, patientDoctorAppointmentListHospital: patientDoctorAppointmentListHospital)))
        .then((value) {
      print("navigation return ");
      dropdownValue = null;
      dropdownTitle = "";
      selectedHospital = null;
      clinicIds = List.empty();
      setState(() {});
      // getProjectsList();
    });
  }

  Future navigateToLaserClinic(BuildContext context) async {
    Navigator.push(
      context,
      FadePage(
        page: LaserClinic(selectedHospital: selectedHospital!),
      ),
    ).then((value) {
      print("LaserBooking navigation return ");
      setState(() {
        dropdownValue = null;
        selectedHospital = null;
        dropdownTitle = "";
        clinicIds = List.empty();
      });
    });
  }

  getDoctorsList(BuildContext context) {
    SearchInfo searchInfo = new SearchInfo();
    if (dropdownValue != null) if (dropdownValue!.split("-")[0] == "17") {
      searchInfo.ProjectID = int.parse(selectedHospital?.mainProjectID.toString() ?? "");
      searchInfo.ClinicID = int.parse(dropdownValue!.split("-")[0]);
      searchInfo.hospital = selectedHospital;
      searchInfo.clinic = selectedClinic;
      searchInfo.date = DateTime.now();

      if (context.read<ProjectViewModel>().isLogin) {
        if (context.read<ProjectViewModel>().user.age! > 12) {
          navigateToDentalComplaints(context, searchInfo);
        } else {
          callDoctorsSearchAPI(17);
        }
      } else {
        navigateToDentalComplaints(context, searchInfo);
      }
    } else if (dropdownValue!.split("-")[0] == "253") {
      navigateToLaserClinic(context);
      // callDoctorsSearchAPI();
    } else if (dropdownValue!.split("-")[1] == "true"
        // && authProvider.isLogin &&
        // authUser.patientType == 1
        ) {
      Navigator.push(
        context,
        FadePage(
          page: LiveCareBookAppointment(clinicName: dropdownTitle, liveCareClinicID: dropdownValue!.split("-")[2], liveCareServiceID: dropdownValue!.split("-")[3]),
        ),
      ).then((value) {
        print("navigation return ");
        if (value == "false") dropdownValue = null;

        // setState(() {
        // });
        if (value == "livecare") {
          Navigator.push(context, FadePage(page: LiveCareHome()));
        }
        if (value == "schedule") {
          callDoctorsSearchAPI(int.parse(dropdownValue!.split("-")[0]));
        }
      });
      setState(() {});
    } else {
      callDoctorsSearchAPI(int.parse(dropdownValue!.split("-")[0]));
    }
  }
}
