import 'dart:async';

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/location_util.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart' show Utils;
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/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/region_bottomsheet/region_list_item.dart' show RegionListItem;
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:lottie/lottie.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../../widgets/common_bottom_sheet.dart';

class RegionBottomSheetBody extends StatefulWidget {
  const RegionBottomSheetBody({super.key});

  @override
  State<RegionBottomSheetBody> createState() => _RegionBottomSheetBodyState();
}

class _RegionBottomSheetBodyState extends State<RegionBottomSheetBody> {
  late BookAppointmentsViewModel myAppointmentsViewModel;
  late AppointmentViaRegionViewmodel regionalViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      regionalViewModel.initSortByLocation();
      if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_REGION || regionalViewModel.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER  ) {
        myAppointmentsViewModel.getRegionMappedProjectList();
      } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_CLINIIC) {
        myAppointmentsViewModel.getMappedDoctors(onError: (err) {
          Navigator.pop(context);
          if (myAppointmentsViewModel.selectedClinic.clinicID == 23) {
            showCommonBottomSheetWithoutHeight(
              context,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Lottie.asset(AppAnimations.errorAnimation, repeat: true, reverse: false, frameRate: FrameRate(60), width: 100.h, height: 100.h, fit: BoxFit.fill),
                  SizedBox(height: 8.h),
                  ("For booking appointments in the Physiotherapy clinic, please contact: 920066666").toText16(color: AppColors.blackColor),
                  SizedBox(height: 16.h),
                  CustomButton(
                      height: 40.h,
                      backgroundColor: AppColors.primaryRedColor,
                      borderColor: AppColors.primaryRedColor,
                      text: LocaleKeys.callNow.tr(),
                      textColor: AppColors.whiteColor,
                      iconColor: AppColors.whiteColor,
                      onPressed: () {
                        launchUrl(
                          Uri.parse("tel://920066666"),
                        );
                      },
                      icon: AppAssets.call),
                ],
              ).center,
              callBackFunc: () {},
              isFullScreen: false,
              isCloseButtonVisible: true,
            );
          } else {
            showCommonBottomSheetWithoutHeight(
              context,
              child: Utils.getErrorWidget(loadingText: err),
              callBackFunc: () {},
              isFullScreen: false,
              isCloseButtonVisible: true,
            );
          }
          // showCommonBottomSheetWithoutHeight(
          //   context,
          //   child: Utils.getErrorWidget(loadingText: err),
          //   callBackFunc: () {},
          //   isFullScreen: false,
          //   isCloseButtonVisible: true,
          // );
        });
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    myAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context);
    regionalViewModel = Provider.of<AppointmentViaRegionViewmodel>(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 SizedBox(
            height: MediaQuery.of(context).size.height * 0.5,
            child: Column(
              children: [
                // AppCustomChipWidget(
                //   richText: Row(
                //     children: [
                //       "${appState.getAuthenticatedUser()!.age} ".toText10(color: AppColors.blackColor, isBold: true),
                //       LocaleKeys.yearsOld.tr(context: context).toText10(color: AppColors.blackColor, isBold: true),
                //     ],
                //   ),
                // ),
                // Consumer<AppointmentViaRegionViewmodel>(
                //   builder: (context, regionVM, _) {
                //     return Padding(
                //       padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 8.h),
                //       child: Row(
                //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
                //         children: [
                //           Row(
                //             children: [
                //               Utils.buildSvgWithAssets(icon: AppAssets.location, iconColor: AppColors.greyTextColor, width: 24.h, height: 24.h),
                //               SizedBox(width: 12.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: regionVM.sortByLocation,
                //             onChanged: (value) => _handleSortByLocationToggle(value),
                //             activeThumbColor: AppColors.successColor,
                //             activeTrackColor: AppColors.successColor.withValues(alpha: 0.15),
                //           ),
                //         ],
                //       ),
                //     );
                //   },
                // ),
                Expanded(
                  child: ListView.separated(
                    itemCount: myAppointmentsVM.hospitalList?.registeredDoctorMap?.length ?? 0,
                    separatorBuilder: (_, __) {
                      return SizedBox(
                        height: 16.h,
                      );
                    },
                    itemBuilder: (_, index) {
                      String key = myAppointmentsVM.hospitalList?.registeredDoctorMap?.keys.toList()[index] ?? '';
                      return RegionListItem(
                        title: key,
                        subTitle: "",
                        hmcCount: "${myAppointmentsVM.hospitalList?.registeredDoctorMap?[key]?.hmcSize ?? 0}",
                        hmgCount: "${myAppointmentsVM.hospitalList?.registeredDoctorMap?[key]?.hmgSize ?? 0}",
                      ).onPress(() {
                        regionalViewModel.setSelectedRegionId(key);
                        regionalViewModel.setDisplayListAndRegionHospitalList(myAppointmentsVM.hospitalList?.registeredDoctorMap![key]);
                        regionalViewModel.setBottomSheetState(AppointmentViaRegionState.HOSPITAL_SELECTION);
                      });
                    },
                  ),
                ),
              ],
            ),
          );
        }
      },
    );
  }

  void _handleSortByLocationToggle(bool value) {
    if (value) {
      // User wants to sort by location — check permission & get location
      final locationUtils = getIt.get<LocationUtils>();
      locationUtils.getLocation(
        isShowConfirmDialog: true,
        onSuccess: (latLng) {
          regionalViewModel.setSortByLocation(true);
          if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_REGION || regionalViewModel.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER) {
            myAppointmentsViewModel.getRegionMappedProjectList();
          } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_CLINIIC) {
            myAppointmentsViewModel.getMappedDoctors();
          }
        },
        onFailure: () {
          showCommonBottomSheetWithoutHeight(
            title: LocaleKeys.notice.tr(context: context),
            context,
            child: Utils.getWarningWidget(
                loadingText: LocaleKeys.giveLocationPermissionForNearestList.tr(context: context),
                isShowActionButtons: true,
                onCancelTap: () {
                  Navigator.of(context).pop();
                },
                onConfirmTap: () async {
                  Navigator.of(context).pop();
                  openAppSettings();
                }),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
          regionalViewModel.setSortByLocation(false);
        },
        onLocationDeniedForever: () {
          showCommonBottomSheetWithoutHeight(
            title: LocaleKeys.notice.tr(context: context),
            context,
            child: Utils.getWarningWidget(
                loadingText: LocaleKeys.giveLocationPermissionForNearestList.tr(context: context),
                isShowActionButtons: true,
                onCancelTap: () {
                  Navigator.of(context).pop();
                },
                onConfirmTap: () async {
                  Navigator.of(context).pop();
                  openAppSettings();
                }),
            callBackFunc: () {},
            isFullScreen: false,
            isCloseButtonVisible: true,
          );
          regionalViewModel.setSortByLocation(false);
        },
      );
    } else {
      // User turned off sort by location — reset location & re-fetch
      final appState = getIt.get<AppState>();
      appState.resetLocation();
      regionalViewModel.setSortByLocation(false);
      if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_REGION || regionalViewModel.regionBottomSheetType == RegionBottomSheetType.REGION_FOR_DENTAL_AND_LASER) {
        myAppointmentsViewModel.getRegionMappedProjectList();
      } else if (regionalViewModel.regionBottomSheetType == RegionBottomSheetType.FOR_CLINIIC) {
        myAppointmentsViewModel.getMappedDoctors();
      }
    }
  }
}
