import 'package:easy_localization/easy_localization.dart' show StringTranslateExtension;
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/enums.dart';
import 'package:hmg_patient_app_new/core/utils/debouncer.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart' show Utils;
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/facility_selection.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/doctor_list_api_response.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/appointments/widgets/hospital_bottom_sheet/hospital_list_items.dart';
import 'package:hmg_patient_app_new/theme/colors.dart' show AppColors;
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:provider/provider.dart';

import '../../../emergency_services/call_ambulance/widgets/type_selection_widget.dart' show TypeSelectionWidget;

// class HospitalBottomSheetBody extends StatelessWidget {
//   late BookAppointmentsViewModel appointmentsViewModel;
//   late AppointmentViaRegionViewmodel regionalViewModel;
//   final TextEditingController searchText = TextEditingController();
//
//   HospitalBottomSheetBody({super.key});
//
//   @override
//   Widget build(BuildContext context) {
//     appointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context);
//     regionalViewModel = Provider.of<AppointmentViaRegionViewmodel>(context);
//     return Column(
//       crossAxisAlignment: CrossAxisAlignment.start,
//       children: [
//         Text(
//           LocaleKeys.selectHospital.tr(context: context),
//           style: TextStyle(
//             fontSize: 21,
//             isBold: true,
//             color: AppColors.blackColor,
//           ),
//         ),
//         Text(
//           LocaleKeys.selectHospitalSubTitle.tr(context: context),
//           style: TextStyle(
//             fontSize: 16,
//             isBold: true,
//             color: AppColors.greyTextColor,
//           ),
//         ),
//         SizedBox(height: 16.h),
//         TextInputWidget(
//           labelText: LocaleKeys.search.tr(context: context),
//           hintText: LocaleKeys.searchHospital.tr(context: context),
//           controller: searchText,
//           onChange: (value) {
//             appointmentsViewModel.filterHospitalListByString(
//                 value, regionalViewModel.selectedRegionId, regionalViewModel.selectedFacilityType == FacilitySelection.HMG.name);
//           },
//           isEnable: true,
//           prefix: null,
//           autoFocus: false,
//           isBorderAllowed: false,
//           keyboardType: TextInputType.text,
//           isAllowLeadingIcon: true,
//           selectionType: SelectionTypeEnum.search,
//           padding: EdgeInsets.symmetric(
//             vertical: ResponsiveExtension(10).h,
//             horizontal: ResponsiveExtension(15).h,
//           ),
//         ),
//         SizedBox(height: 24.h),
//         // TypeSelectionWidget(
//         //   hmcCount: "0",
//         //   hmgCount: "0",
//         // ),
//         // SizedBox(height: 21.h),
//         SizedBox(
//           height: MediaQuery.sizeOf(context).height * .4,
//           child: ListView.separated(
//               itemBuilder: (_, index) {
//                 var hospital = regionalViewModel.selectedFacilityType == FacilitySelection.HMG.name
//                     ? appointmentsViewModel.filteredHospitalList!.registeredDoctorMap![regionalViewModel.selectedRegionId!]!.hmgDoctorList![index]
//                     : appointmentsViewModel.filteredHospitalList?.registeredDoctorMap?[regionalViewModel.selectedRegionId!]?.hmcDoctorList?[index];
//                 return HospitalListItem(
//                   hospitalData: hospital,
//                   isLocationEnabled: appointmentsViewModel.isLocationEnabled(),
//                 ).onPress(() {
//                   regionalViewModel.setHospitalModel(hospital);
//                   if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_REGION) {
//                     regionalViewModel.setBottomSheetState(AppointmentViaRegionState.CLINIC_SELECTION);
//                     regionalViewModel.handleLastStepForRegion();
//                   } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_CLINIIC) {
//                     regionalViewModel.setBottomSheetState(AppointmentViaRegionState.DOCTOR_SELECTION);
//                     regionalViewModel.handleLastStepForClinic();
//                   } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER) {
//                     regionalViewModel.setBottomSheetState(AppointmentViaRegionState.DOCTOR_SELECTION);
//                     regionalViewModel.handleLastStepForClinicForDentalAndLaser(appointmentsViewModel.selectedClinic.clinicID ?? -1);
//                     // regionalViewModel.handleLastStepForClinic();
//                   }
//                 });
//               },
//               separatorBuilder: (_, __) => SizedBox(
//                     height: 16.h,
//                   ),
//               itemCount: (regionalViewModel.selectedFacilityType == FacilitySelection.HMG.name
//                           ? (appointmentsViewModel.filteredHospitalList?.registeredDoctorMap?[regionalViewModel.selectedRegionId]?.hmgDoctorList)
//                           : (appointmentsViewModel.filteredHospitalList?.registeredDoctorMap?[regionalViewModel.selectedRegionId]?.hmcDoctorList))
//                       ?.length ??
//                   0),
//         )
//       ],
//     );
//   }
// }

class HospitalBottomSheetBody extends StatelessWidget {

  final TextEditingController searchText ;
  final Debouncer  debouncer = Debouncer(milliseconds: 500);

  final int hmcCount;
  final int hmgCount;
  final List<PatientDoctorAppointmentList>? displayList;
  final FacilitySelection selectedFacility;
  final Function(FacilitySelection) onFacilityClicked;
  final Function(PatientDoctorAppointmentList) onHospitalClicked;
  final Function(String) onHospitalSearch;
  final bool sortByLocation;
  final Function(bool)? onSortByLocationToggle;

  HospitalBottomSheetBody({super.key, required this.hmcCount, required this.hmgCount, this.displayList, required this.selectedFacility, required this.onFacilityClicked, required this.onHospitalClicked, required this.onHospitalSearch, required this.searchText, this.sortByLocation = false, this.onSortByLocationToggle});

  @override
  Widget build(BuildContext context) {
    return Consumer<BookAppointmentsViewModel>(builder: (context, myAppointmentsVM, child) {
      if (myAppointmentsVM.isRegionListLoading) {
        return Container(
          height: MediaQuery.of(context).size.height * 0.3,
          decoration: BoxDecoration(
            color: AppColors.whiteColor,
            borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
          ),
          child: Center(
            child: Utils.getLoadingWidget(),
          ),
        );
      } else {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextInputWidget(
              labelText: LocaleKeys.search.tr(context: context),
              hintText: LocaleKeys.searchHospital.tr(context: context),
              controller: searchText,
              onChange: (value) {
                debouncer.run(() {
                  onHospitalSearch(value ?? "");
                });
              },
              isEnable: true,
              prefix: null,
              autoFocus: false,
              isBorderAllowed: false,
              keyboardType: TextInputType.text,
              isAllowLeadingIcon: true,
              selectionType: SelectionTypeEnum.search,
              padding: EdgeInsets.symmetric(
                vertical: ResponsiveExtension(10).h,
                horizontal: ResponsiveExtension(15).h,
              ),
            ),
            SizedBox(height: 16.h),
            if (onSortByLocationToggle != null)
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 4.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Utils.buildSvgWithAssets(icon: AppAssets.location, iconColor: AppColors.greyTextColor, width: 18.h, height: 18.h),
                        SizedBox(width: 8.w),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            LocaleKeys.sortByLocation.tr(context: context).toText14(isBold: true),
                            // SizedBox(height: 4.h),
                            LocaleKeys.sortByNearestLocation.tr(context: context).toText11(color: AppColors.textColorLight, isBold: true),
                          ],
                        ),
                      ],
                    ),
                    Switch(
                      value: sortByLocation,
                      onChanged: onSortByLocationToggle,
                      activeThumbColor: AppColors.successColor,
                      activeTrackColor: AppColors.successColor.withValues(alpha: 0.15),
                    ),
                  ],
                ),
              ),
            if (onSortByLocationToggle != null) SizedBox(height: 8.h),
            TypeSelectionWidget(
              selectedFacility: selectedFacility,
              hmcCount: hmcCount.toString(),
              hmgCount: hmgCount.toString(),
              onitemClicked: (selectedValue) {
                onFacilityClicked(selectedValue);
              },
            ),
            SizedBox(height: 21.h),
            SizedBox(
                height: MediaQuery.sizeOf(context).height * .4,
                child: ListView.separated(
                  itemBuilder: (_, index) {
                    var hospital = displayList?[index];
                    return HospitalListItem(
                      hospitalData: hospital,
                      isLocationEnabled: sortByLocation,
                    ).onPress(() {
                      onHospitalClicked(hospital!);
                    });
                  },
                  separatorBuilder: (_, __) => SizedBox(
                    height: 16.h,
                  ),
                  itemCount: displayList?.length ?? 0,
                ))
          ],
        );
      }
    });
  }
}

