import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/config/shared_pref_kay.dart';
import 'package:hmg_patient_app/pages/BookAppointment/components/LaserClinic.dart';
import 'package:hmg_patient_app/pages/BookAppointment/search_result/SearchResultWithTab.dart';
import 'package:hmg_patient_app/pages/BookAppointment/search_result/SearchResultWithTabForHospital.dart';
import 'package:hmg_patient_app/services/appointment_services/doctor_response_mapper.dart';
import 'package:hmg_patient_app/uitl/location_util.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.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 'LiveCareBookAppointment.dart';

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

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

  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 = "";
  late LocationUtils locationUtils;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
      // locationUtils.getCurrentLocation();
      // getProjectsList();
      locationUtils = new LocationUtils(isShowConfirmDialog: false, context: context);
      locationUtils.getCurrentLocation(callBack: (_) {
        getProjectsList();
      }, onConsentDeclined: () {
        getProjectsList();
      });
      // getProjectsList();
    });
  }

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

  @override
  void reassemble() {
    super.reassemble();
  } // @override
  // void didChangeDependencies() {
  //   WidgetsBinding.instance.addPostFrameCallback((_) {
  //     getProjectsList();
  //   });
  // }

  // @override
  // void didUpdateWidget(SearchByHospital oldWidget) {
  //   WidgetsBinding.instance.addPostFrameCallback((_) {
  //     getProjectsList();
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    AppGlobal.context = context;
    return (hospitalList != null)
        ? SearchResultWithTabForHospital(
            patientDoctorAppointmentListHospital: hospitalList!,
            doctorsList: [],
            isDoctorSearchResult: false,
            isLiveCareAppointment: false,
          )
        : SizedBox.shrink();
    // 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() {
    AppGlobal.context = context;
    GifLoaderDialogUtils.showMyDialog(context);
    int languageID = context.read<ProjectViewModel>().isArabic ? 1 : 2;
    ClinicListService service = new ClinicListService();
    List<HospitalsModel> projectsListLocal = [];
    service.getProjectsList(languageID, context).then((res) async {
      if (res['MessageStatus'] == 1) {
        res['ListProject'].forEach((v) {
          projectsListLocal.add(new HospitalsModel.fromJson(v));
        });
        projectsList = projectsListLocal;
        hospitalList = await DoctorMapper.getMappedHospitals(projectsList, isArabic: context.read<ProjectViewModel>().isArabic);
        var lat = await sharedPref.getDouble(USER_LAT);

        var lng = await sharedPref.getDouble(USER_LONG);
        var isLocationEnabled = (lat != null && lat != 0.0) && (lng != null && lng != 0.0);
        hospitalList = await DoctorMapper.sortList(isLocationEnabled, hospitalList!);
        setState(() {});
        GifLoaderDialogUtils.hideDialog(context);
      } else {}
      GifLoaderDialogUtils.hideDialog(context);
      // locationUtils.getCurrentLocation();
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      // locationUtils.getCurrentLocation();
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      // locationUtils.getCurrentLocation();
      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) {
    var isArabic = context.read<ProjectViewModel>().isArabic;
    int languageID = 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) async {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        RegionList regionHospitalList = RegionList();

        if (res['DoctorList'].length != 0) {
          res['DoctorList'].forEach((v) {
            doctorsList.add(new DoctorList.fromJson(
              v,
            ));
          });

          regionHospitalList = await DoctorMapper.getMappedDoctor(doctorsList, isArabic: isArabic);
          var lat = await sharedPref.getDouble(USER_LAT);

          var lng = await sharedPref.getDouble(USER_LONG);
          var isLocationEnabled = (lat != null && lat != 0.0) && (lng != null && lng != 0.0);
          regionHospitalList = await DoctorMapper.sortList(isLocationEnabled, regionHospitalList);

          setState(() {});
        } else {
          GifLoaderDialogUtils.hideDialog(context);
          AppToast.showErrorToast(message: res['ErrorSearchMsg']);
        }

        GifLoaderDialogUtils.hideDialog(context);
        // navigateToSearchResults(context, doctorsList, _patientDoctorAppointmentListHospital);
        navigateToSearchResults(context, regionHospitalList);
      } else {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      print(err);
      AppToast.showErrorToast(message: err, localContext: context);
    });
  }

  navigateToSearchResults(context, RegionList regionHospitalList) {
    // Navigator.push(context,
    //     FadePage(page: SearchResults(isLiveCareAppointment: false, isDoctorNameSearch: true, doctorsList: docList, patientDoctorAppointmentListHospital: patientDoctorAppointmentListHospital, isDoctorSearchResult: true,)));
    Navigator.push(
      context,
      FadePage(
        page: SearchResultWithTab(
          doctorsList: [],
          patientDoctorAppointmentListHospital: regionHospitalList,
          isLiveCareAppointment: false,
          isDoctorSearchResult: true,
        ),
      ),
    );
  }

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