import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/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/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/doctor_filter/doctor_filter_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/appointment_via_region_viewmodel.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_bottom_sheet_body_for_doctor_filter.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_filter/RegionChips.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_filter/clinic_bottomsheet.dart';
import 'package:hmg_patient_app_new/presentation/book_appointment/doctor_filter/facility_Chips.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:provider/provider.dart';

import '../../../widgets/buttons/custom_button.dart';

class DoctorsFilters extends StatelessWidget{


  TextEditingController hospitalController = TextEditingController();
  TextEditingController clinicController = TextEditingController();
  DoctorsFilters({super.key,});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      appBar: AppBar(
          backgroundColor: AppColors.bgScaffoldColor,

        automaticallyImplyLeading: false,
      centerTitle: false,
      title:  Utils.buildSvgWithAssets(icon: AppAssets.ic_close, height: 32.h, width: 32.h).onPress((){
        context.read<DoctorFilterViewModel>()
            .clearSelection()
        ;
        Navigator.pop(context);
      })



      ),

      body: Column(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                      LocaleKeys.filters.tr(),
                    style:TextStyle(
                      fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                        fontWeight: FontWeight.w600,
                      fontSize: 27.f,
                      color: AppColors.textColor,
                      letterSpacing: -1
                    )
                  ),
                  Text(
                      LocaleKeys.clearAllFilters.tr(),
                      style:TextStyle(
                          fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                          fontWeight: FontWeight.w600,
                          fontSize: 14.f,
                          color: AppColors.errorColor
                      )
                  ).onPress((){
                    context.read<DoctorFilterViewModel>().clearSelection();
                    context.read<DoctorFilterViewModel>().updateApplyFilters(false);
                    // context.read<BookAppointmentsViewModel>().setSelections(
                    //     context.read<DoctorFilterViewModel>().selectedFacilityForFilters,
                    //     context.read<DoctorFilterViewModel>().selectedRegionForFilters,
                    //     context.read<DoctorFilterViewModel>().selectedClinicForFilters,
                    //     context.read<DoctorFilterViewModel>().selectedHospitalForFilters,
                    //     context.read<DoctorFilterViewModel>().applyFilters);
                    context.read<BookAppointmentsViewModel>().updateList();
                  })
                ],
              ),
              titleWidget(LocaleKeys.regionAndLocation.tr()),
              SizedBox(
                  height: 42.h,
                  child: RegionChips()),
              titleWidget(LocaleKeys.facilityAndLocation.tr()),
              SizedBox(
                  height: 42.h,
                  child: FacilityChip()),
              titleWidget(LocaleKeys.hospital.tr()),
              Consumer<DoctorFilterViewModel>(
                builder: (context, viewModel, child) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      TextInputWidget(
                        controller: TextEditingController()..text = viewModel.selectedHospitalForFilters?.filterName ?? '',
                        labelText: LocaleKeys.hospital.tr(context: context),
                        hintText: LocaleKeys.searchHospital.tr(context: context),
                        isEnable: false,
                        prefix: null,
                        autoFocus: false,
                        isBorderAllowed: true,
                        keyboardType: TextInputType.text,
                        hasError: viewModel.hospitalError != null,
                        errorMessage: viewModel.hospitalError,
                        suffix: viewModel.selectedHospitalForFilters != null
                            ? GestureDetector(
                                onTap: () {
                                  viewModel.setSelectedHospital(null);
                                },
                                child: Utils.buildSvgWithAssets(icon: AppAssets.ic_cross_circle, width: 24.h, height: 24.h, fit: BoxFit.scaleDown),
                              )
                            : null,
                        onChange: (value) {
                          // Clear error when field changes
                          viewModel.clearHospitalError();
                        },
                        padding: EdgeInsets.symmetric(
                          vertical: ResponsiveExtension(8).h,
                          horizontal: ResponsiveExtension(10).h,
                        ),
                      ).onPress(() {
                        // Clear error when opening bottom sheet
                        context.read<DoctorFilterViewModel>().clearHospitalError();
                        openRegionListBottomSheet(context, RegionBottomSheetType.FOR_REGION);
                      }),
                    ],
                  );
                },
              ),

              titleWidget(LocaleKeys.clinic.tr()),
              Consumer<DoctorFilterViewModel>(
                builder: (context, viewModel, child) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      TextInputWidget(
                        controller: TextEditingController()..text = viewModel.selectedClinicForFilters ?? '',
                        labelText: LocaleKeys.clinicName.tr(context: context),
                        hintText: LocaleKeys.searchClinic.tr(),
                        isEnable: false,
                        prefix: null,
                        autoFocus: false,
                        isBorderAllowed: true,
                        keyboardType: TextInputType.text,
                        hasError: viewModel.clinicError != null,
                        errorMessage: viewModel.clinicError,
                        suffix: viewModel.selectedClinicForFilters?.isNotEmpty == true
                            ? GestureDetector(
                                onTap: () {
                                  viewModel.setSelectedClinicForFilter(null);
                                },
                                child: Utils.buildSvgWithAssets(icon: AppAssets.ic_cross_circle, width: 20.h, height: 20.h, fit: BoxFit.scaleDown),
                              )
                            : null,
                        onChange: (value) {
                          // Clear error when field changes
                          viewModel.clearClinicError();
                        },
                        padding: EdgeInsets.symmetric(
                          vertical: 8.h,
                          horizontal: 10.h,
                        ),
                      ).onPress(() {
                        // Clear error when opening bottom sheet
                        context.read<DoctorFilterViewModel>().clearClinicError();
                        openClinicListBottomSheet(context);
                      }),
                    ],
                  );
                },
              ),


            ],
          ).paddingSymmetrical(24.h, 0.h),
          Spacer(),
          DecoratedBox(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              customBorder:  BorderRadius.only(topLeft: Radius.circular(24.h), topRight: Radius.circular(24.h)) ,

            ),
            child: CustomButton(
              text: LocaleKeys.applyFilter.tr(),
              onPressed: () {
                context.read<DoctorFilterViewModel>().updateApplyFilters(true);
                context.read<BookAppointmentsViewModel>().setSelections(
                    context.read<DoctorFilterViewModel>().selectedFacilityForFilters?.toList()??[],
                    context.read<DoctorFilterViewModel>().selectedRegionForFilters?.toList()??[],
                    context.read<DoctorFilterViewModel>().selectedClinicForFilters,
                    context.read<DoctorFilterViewModel>().selectedHospitalForFilters,
                    context.read<DoctorFilterViewModel>().applyFilters);
                context.read<BookAppointmentsViewModel>().updateList();
                Navigator.pop(context);
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: Colors.white,
              fontSize: 16.f,
              padding: EdgeInsets.zero,
              fontWeight: FontWeight.w600,
              borderRadius: 10.r,
              icon: AppAssets.add_icon,
              iconColor: AppColors.primaryRedColor,
            ).paddingAll(24.h),
          ),
        ],
      ),
    );
  }

  Widget titleWidget(String title){
    return Column(
      children: [
        SizedBox(height: 24.h,),
        Text(
            title,
            style:TextStyle(
                fontFamily: getIt.get<AppState>().isArabic() ? 'CairoArabic' : 'Poppins',
                fontWeight: FontWeight.w600,
                fontSize: 16.f,
                color: AppColors.textColor,
                letterSpacing:-1
            )
        ),
        SizedBox(height: 8.h,),
      ],
    );
  }

   void openRegionListBottomSheet(BuildContext context, RegionBottomSheetType type) {
     context.read<AppointmentViaRegionViewmodel>().flush();
     context.read<AppointmentViaRegionViewmodel>().setBottomSheetType(type);
     context.read<AppointmentViaRegionViewmodel>().setBottomSheetState(AppointmentViaRegionState.HOSPITAL_SELECTION);
     // AppointmentViaRegionViewmodel? viewmodel = null;
     showCommonBottomSheetWithoutHeight(context, title: "", titleWidget: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) => getTitle(data)), isDismissible: false,
         child: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) {
           return getRegionalSelectionWidget(data);
         }), callBackFunc: () {});
   }

   Widget getRegionalSelectionWidget(AppointmentViaRegionViewmodel data) {

     if (data.bottomSheetState == AppointmentViaRegionState.HOSPITAL_SELECTION) {
       return HospitalBottomSheetBodyForDoctorFilter();
     }
     if (data.bottomSheetState == AppointmentViaRegionState.CLINIC_SELECTION) {
      } else {
       SizedBox.shrink();
     }
     return SizedBox.shrink();
   }

   getTitle(AppointmentViaRegionViewmodel data) {
    return SizedBox.shrink();
   }

  void openClinicListBottomSheet(BuildContext context) {
    showCommonBottomSheetWithoutHeight(context, title: "", titleWidget: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) => getTitle(data)), isDismissible: false,
        child: Consumer<AppointmentViaRegionViewmodel>(builder: (_, data, __) {
          return ClinicBottomSheet();
        }), callBackFunc: () {});
  }

}