import 'dart:async';

import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:staff_authentication/src/presentation/blocs/profile_setup/profile_setup_bloc.dart';
import 'package:staff_authentication/src/presentation/widgets/common/section_title_subtitle.dart';

/// A widget for setting up preferred work locations and distance.
class ProfileSetupLocation extends StatefulWidget {
  /// The list of preferred locations.
  final List<String> preferredLocations;

  /// The maximum distance in miles.
  final double maxDistanceMiles;

  /// Callback for when the preferred locations list changes.
  final ValueChanged<List<String>> onLocationsChanged;

  /// Callback for when the max distance changes.
  final ValueChanged<double> onDistanceChanged;

  /// Creates a [ProfileSetupLocation] widget.
  const ProfileSetupLocation({
    super.key,
    required this.preferredLocations,
    required this.maxDistanceMiles,
    required this.onLocationsChanged,
    required this.onDistanceChanged,
  });

  @override
  State<ProfileSetupLocation> createState() => _ProfileSetupLocationState();
}

class _ProfileSetupLocationState extends State<ProfileSetupLocation> {
  final TextEditingController _locationController = TextEditingController();
  Timer? _debounce;

  @override
  void dispose() {
    _locationController.dispose();
    _debounce?.cancel();
    super.dispose();
  }

  void _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();
    _debounce = Timer(const Duration(milliseconds: 300), () {
      context.read<ProfileSetupBloc>().add(
        ProfileSetupLocationQueryChanged(query),
      );
    });
  }

  /// Adds the selected location.
  void _addLocation(String location) {
    if (location.isNotEmpty && !widget.preferredLocations.contains(location)) {
      final List<String> updatedList = List<String>.from(
        widget.preferredLocations,
      )..add(location);
      widget.onLocationsChanged(updatedList);
      _locationController.clear();
      context.read<ProfileSetupBloc>().add(
        const ProfileSetupClearLocationSuggestions(),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SectionTitleSubtitle(
          title: t.staff_authentication.profile_setup_page.location.title,
          subtitle: t.staff_authentication.profile_setup_page.location.subtitle,
        ),
        const SizedBox(height: UiConstants.space8),

        // Search Input
        UiTextField(
          label: t
              .staff_authentication
              .profile_setup_page
              .location
              .add_location_label,
          controller: _locationController,
          hintText: t
              .staff_authentication
              .profile_setup_page
              .location
              .add_location_hint,
          onChanged: _onSearchChanged,
        ),

        // Suggestions List
        BlocBuilder<ProfileSetupBloc, ProfileSetupState>(
          buildWhen: (previous, current) =>
              previous.locationSuggestions != current.locationSuggestions,
          builder: (context, state) {
            if (state.locationSuggestions.isEmpty) {
              return const SizedBox.shrink();
            }
            return Container(
              constraints: const BoxConstraints(maxHeight: 200),
              margin: const EdgeInsets.only(top: UiConstants.space2),
              decoration: BoxDecoration(
                color: UiColors.cardViewBackground,
                borderRadius: UiConstants.radiusMd,
              ),
              child: ListView.separated(
                shrinkWrap: true,
                padding: EdgeInsets.zero,
                itemCount: state.locationSuggestions.length,
                separatorBuilder: (context, index) => const Divider(height: 1),
                itemBuilder: (context, index) {
                  final suggestion = state.locationSuggestions[index];
                  return ListTile(
                    title: Text(suggestion, style: UiTypography.body2m),
                    leading: const Icon(UiIcons.mapPin, size: 16),
                    onTap: () => _addLocation(suggestion),
                    visualDensity: VisualDensity.compact,
                  );
                },
              ),
            );
          },
        ),

        const SizedBox(height: UiConstants.space4),

        // Location Badges
        if (widget.preferredLocations.isNotEmpty)
          Wrap(
            spacing: UiConstants.space2,
            runSpacing: UiConstants.space2,
            children: widget.preferredLocations.map((String loc) {
              return UiChip(
                label: loc,
                leadingIcon: UiIcons.mapPin,
                trailingIcon: UiIcons.close,
                onTrailingIconTap: () => _removeLocation(location: loc),
                variant: UiChipVariant.secondary,
              );
            }).toList(),
          ),

        const SizedBox(height: UiConstants.space8),
        // Slider
        Text(
          t.staff_authentication.profile_setup_page.location.max_distance(
            distance: widget.maxDistanceMiles.round().toString(),
          ),
          style: UiTypography.body2m,
        ),
        const SizedBox(height: UiConstants.space2),
        Slider(
          value: widget.maxDistanceMiles,
          min: 5,
          max: 50,
          onChanged: widget.onDistanceChanged,
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: UiConstants.space2),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                t
                    .staff_authentication
                    .profile_setup_page
                    .location
                    .min_dist_label,
                style: UiTypography.footnote1r.textSecondary,
              ),
              Text(
                t
                    .staff_authentication
                    .profile_setup_page
                    .location
                    .max_dist_label,
                style: UiTypography.footnote1r.textSecondary,
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// Removes the specified [location] from the list.
  void _removeLocation({required String location}) {
    final List<String> updatedList = List<String>.from(
      widget.preferredLocations,
    )..remove(location);
    widget.onLocationsChanged(updatedList);
  }
}
