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/doctor_response_mapper.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/habib_wallet/habib_wallet_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/hospital_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/habib_wallet/widgets/hospital_list_item.dart';
import 'package:hmg_patient_app_new/theme/colors.dart' show AppColors;
import 'package:hmg_patient_app_new/widgets/common_bottom_sheet.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

class SelectHospitalBottomSheet extends StatefulWidget {
  /// Optional callback invoked when the user picks a hospital.
  /// When provided, the caller handles the selection instead of the default
  /// [HabibWalletViewModel.setSelectedHospital] behaviour.
  final void Function(HospitalsModel hospital)? onHospitalSelected;

  const SelectHospitalBottomSheet({super.key, this.onHospitalSelected});

  @override
  State<SelectHospitalBottomSheet> createState() => _SelectHospitalBottomSheetState();
}

class _SelectHospitalBottomSheetState extends State<SelectHospitalBottomSheet> {
  late HabibWalletViewModel habibWalletVM;
  final TextEditingController searchText = TextEditingController();
  bool sortByLocation = false;
  bool isLoading = false;
  List<HospitalsModel> displayList = [];

  @override
  void initState() {
    super.initState();
    final appState = getIt.get<AppState>();
    sortByLocation = (appState.userLat != 0.0) && (appState.userLong != 0.0);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _updateDisplayList();
    });
  }

  void _updateDisplayList() {
    final appState = getIt.get<AppState>();
    final hospitals = List<HospitalsModel>.from(habibWalletVM.advancePaymentHospitals);

    if (sortByLocation && appState.userLat != 0.0 && appState.userLong != 0.0) {
      hospitals.sort((a, b) {
        final distA = (a.latitude != null && a.longitude != null)
            ? DoctorMapper.calculateDistance(appState.userLat, appState.userLong, double.parse(a.latitude!), double.parse(a.longitude!))
            : double.infinity;
        final distB = (b.latitude != null && b.longitude != null)
            ? DoctorMapper.calculateDistance(appState.userLat, appState.userLong, double.parse(b.latitude!), double.parse(b.longitude!))
            : double.infinity;
        return distA.compareTo(distB);
      });
    }

    setState(() {
      displayList = hospitals;
      isLoading = false;
    });
  }

  void _refreshHospitalListAfterApi() {
    void listener() {
      if (habibWalletVM.advancePaymentHospitals.isNotEmpty) {
        habibWalletVM.removeListener(listener);
        _updateDisplayList();
      }
    }

    habibWalletVM.addListener(listener);
    habibWalletVM.getProjectsList();
  }

  void _handleSortByLocationToggle(bool value) {
    if (value) {
      final locationUtils = getIt.get<LocationUtils>();
      locationUtils.getLocation(
        isShowConfirmDialog: true,
        onSuccess: (latLng) {
          setState(() {
            sortByLocation = true;
            isLoading = true;
          });
          _refreshHospitalListAfterApi();
        },
        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,
          );
          setState(() {
            sortByLocation = 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,
          );
          setState(() {
            sortByLocation = false;
          });
        },
      );
    } else {
      final appState = getIt.get<AppState>();
      appState.resetLocation();
      setState(() {
        sortByLocation = false;
        isLoading = true;
      });
      _refreshHospitalListAfterApi();
    }
  }

  @override
  Widget build(BuildContext context) {
    habibWalletVM = Provider.of<HabibWalletViewModel>(context, listen: false);
    if (displayList.isEmpty && habibWalletVM.advancePaymentHospitals.isNotEmpty) {
      displayList = List.from(habibWalletVM.advancePaymentHospitals);
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          LocaleKeys.selectHospitalForAdvancePayment.tr(context: context),
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: AppColors.greyTextColor,
          ),
        ),
        SizedBox(height: 16.h),
        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),
                      LocaleKeys.sortByNearestLocation.tr(context: context).toText11(color: AppColors.textColorLight, isBold: true),
                    ],
                  ),
                ],
              ),
              Switch(
                value: sortByLocation,
                onChanged: _handleSortByLocationToggle,
                activeThumbColor: AppColors.successColor,
                activeTrackColor: AppColors.successColor.withValues(alpha: 0.15),
              ),
            ],
          ),
        ),
        SizedBox(height: 8.h),
        isLoading
            ? SizedBox(
                height: MediaQuery.sizeOf(context).height * .4,
                child: Center(child: Utils.getLoadingWidget()),
              )
            : SizedBox(
                height: MediaQuery.sizeOf(context).height * .4,
                child: ListView.separated(
                    itemBuilder: (_, index) {
                      return HospitalListItemAdvancePayment(
                        hospitalModel: displayList[index],
                        isLocationEnabled: sortByLocation,
                      ).onPress(() {
                        if (widget.onHospitalSelected != null) {
                          widget.onHospitalSelected!(displayList[index]);
                        } else {
                          habibWalletVM.setSelectedHospital(displayList[index]);
                        }
                        Navigator.of(context).pop();
                      });
                    },
                    separatorBuilder: (_, __) => SizedBox(
                          height: 16.h,
                        ),
                    itemCount: displayList.length),
              )
      ],
    );
  }
}
