import 'package:easy_localization/easy_localization.dart' show tr, StringTranslateExtension;
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:hmg_patient_app_new/core/app_assets.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';
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/emergency_services/emergency_services_view_model.dart';
import 'package:hmg_patient_app_new/features/emergency_services/models/resp_model/ProjectAvgERWaitingTime.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/emergency_services/widgets/nearestERItem.dart' show NearestERItem;
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/widgets/input_widget.dart';
import 'package:provider/provider.dart' show Selector, WatchContext, ReadContext;

import '../../core/utils/debouncer.dart' show Debouncer;

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

  @override
  State<NearestErPage> createState() => _NearestErPageState();
}

class _NearestErPageState extends State<NearestErPage> {
  final TextEditingController searchText = TextEditingController();
  final Debouncer debouncer = Debouncer(milliseconds: 500);

  @override
  void initState() {
    super.initState();
    _checkLocationAndFetchER();
  }

  void _checkLocationAndFetchER() {
    final emergencyServicesViewModel = context.read<EmergencyServicesViewModel>();

    // Check if location utils is available and get location with permission check
    if (emergencyServicesViewModel.locationUtils != null) {
      emergencyServicesViewModel.locationUtils!.getLocation(
        isShowConfirmDialog: true,
        onSuccess: (position) {
          // Location permission granted and location received
          emergencyServicesViewModel.getNearestER();
        },
        onFailure: () {
          // Location permission denied or failed, still fetch ER list without location sorting
          emergencyServicesViewModel.getNearestER();
        },
      );
    } else {
      // No location utils available, just fetch the ER list
      emergencyServicesViewModel.getNearestER();
    }
  }

  @override
  void dispose() {
    debouncer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CollapsingListView(
        title: LocaleKeys.nearester.tr(context: context),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: [
              TextInputWidget(
                labelText: LocaleKeys.search.tr(),
                hintText: '',
                controller: searchText,
                onChange: (value) {
                  debouncer.run(() {
                    context.read<EmergencyServicesViewModel>().filterErList(value ?? '');
                  });
                },
                isEnable: true,
                prefix: null,
                autoFocus: false,
                isBorderAllowed: false,
                keyboardType: TextInputType.text,
                isAllowLeadingIcon: true,
                leadingIcon: AppAssets.search_icon,
                padding: EdgeInsets.symmetric(
                  vertical: ResponsiveExtension(10).h,
                  horizontal: ResponsiveExtension(15).h,
                ),
              ),
              Selector<EmergencyServicesViewModel, bool>(
                selector: (___, viewModel) => viewModel.isERListLoading,
                builder: (_, isLoading, __) => Selector<EmergencyServicesViewModel, List<ProjectAvgERWaitingTime>>(
                    selector: (___, viewModel) => viewModel.nearestERFilteredList,
                    shouldRebuild: (previous, next) => previous != next,
                    builder: (_, value, __) {
                      if (isLoading || value.isNotEmpty) {
                        return ListView.separated(
                          padding: EdgeInsets.only(top: 24.h),
                          itemCount: isLoading ? 6 : value.length,
                          separatorBuilder: (____, _____) => SizedBox(
                            height: 16.h,
                          ),
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemBuilder: (context, index) {
                            return AnimationConfiguration.staggeredList(
                                position: index,
                                duration: const Duration(milliseconds: 500),
                                child: SlideAnimation(
                                    verticalOffset: 100.0,
                                    child: FadeInAnimation(
                                        child: NearestERItem(
                                      isLoading: isLoading,
                                      nearestERItem: isLoading ? ProjectAvgERWaitingTime() : value[index],
                                    ))));
                          },
                        );
                      } else {
                        return Center(child: Utils.getNoDataWidget(context, noDataText: LocaleKeys.noNearestER.tr()));
                      }
                    }),
              ),
            ],
          ).paddingAll(16.h),
        ));
  }
}
