import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/core/model/hospitals/hospitals_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/models/Appointments/SearchInfoModel.dart';
import 'package:hmg_patient_app/models/Clinics/ClinicListResponse.dart';
import 'package:hmg_patient_app/pages/BookAppointment/DentalComplaints.dart';
import 'package:hmg_patient_app/pages/BookAppointment/components/LaserClinic.dart';
import 'package:hmg_patient_app/pages/BookAppointment/components/LiveCareBookAppointment.dart';
import 'package:hmg_patient_app/pages/livecare/livecare_home.dart';
import 'package:hmg_patient_app/services/appointment_services/GetDoctorsList.dart';
import 'package:hmg_patient_app/services/appointment_services/doctor_response_mapper.dart';
import 'package:hmg_patient_app/services/clinic_services/get_clinic_service.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../../config/shared_pref_kay.dart';
import '../../../models/Appointments/DoctorListResponse.dart';
import '../../../services/authentication/auth_provider.dart';
import '../../../theme/colors.dart';
import '../../../uitl/gif_loader_dialog_utils.dart';

class ResultByClinic extends StatefulWidget {
  HospitalsModel? selectedValue;
  Function(RegionList, int?) onClinicSelected;

  ResultByClinic({super.key, this.selectedValue, required this.onClinicSelected});

  @override
  State<ResultByClinic> createState() => _ResultByClinicState();
}

class _ResultByClinicState extends State<ResultByClinic> {
  List<ListClinicCentralized>? clinicIds = List.empty();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) => getClinicWrtHospital(widget.selectedValue));
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
            child: clinicIds?.isNotEmpty == true
                ? ListView.builder(
                    itemBuilder: (_, index) => InkWell(
                      onTap: () {
                        getDoctorsList(
                            context,
                            "${clinicIds?[index].clinicID.toString() ?? ''}-${clinicIds?[index].isLiveCareClinicAndOnline!.toString()}-${clinicIds?[index].liveCareClinicID.toString()}-${clinicIds?[index].liveCareServiceID.toString()}",
                            clinicIds?[index].clinicDescription!,
                            widget.selectedValue,
                            clinicIds?[index]);
                      },
                      child: Material(
                        color: CustomColors.white,
                        child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
                            child: Row(
                              children: [
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        clinicIds?[index].clinicDescription ?? '',
                                        style: TextStyle(fontSize: 22, color: Colors.black, fontWeight: FontWeight.w700),
                                      ),
                                    ],
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.all(8),
                                  child: Center(
                                    child: Icon(
                                      Icons.arrow_forward_ios,
                                      color: CustomColors.black,
                                      size: 16,
                                    ),
                                  ),
                                ),
                              ],
                            )),
                      ),
                    ),
                    itemCount: clinicIds?.length ?? 0,
                  )
                : getNoDataWidget(context)),
      ],
    );
  }

  getDoctorsList(BuildContext context, String? dropdownValue, String? dropdownTitle, HospitalsModel? selectedHospital, ListClinicCentralized? selectedClinic) {
    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") return;

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

  Future navigateToLaserClinic(BuildContext context) async {
    Navigator.push(
      context,
      FadePage(
        page: LaserClinic(selectedHospital: widget.selectedValue!),
      ),
    ).then((value) {});
  }

  Future navigateToDentalComplaints(BuildContext context, SearchInfo searchInfo) async {
    Navigator.push(
      context,
      FadePage(
        page: DentalComplaints(
          searchInfo: searchInfo,
          isFromHospitalSearchPage: true,
        ),
      ),
    ).then((value) {
      if (value is RegionList) {
        widget.onClinicSelected(value,null);
      }
    });
  }

  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, widget.selectedValue?.mainProjectID.toString() != "" ? int.parse(widget.selectedValue?.mainProjectID.toString() ?? "-1") : 0, false, 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);
          widget.onClinicSelected(regionHospitalList,  clinicID);
          setState(() {});
        } else {
          GifLoaderDialogUtils.hideDialog(context);
          AppToast.showErrorToast(message: res['ErrorSearchMsg']);
        }

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

  void getClinicWrtHospital(HospitalsModel? newValue) async {
    AppGlobal.context = context;
    GifLoaderDialogUtils.showMyDialog(context);
    ClinicListService service = new ClinicListService();
    List<HospitalsModel> projectsListLocal = [];
    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);
    }
  }
}
