import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/auth/data/models/administrative_division.dart';
import 'package:sigap/src/features/map/data/repositories/location_repository.dart';
import 'package:sigap/src/features/auth/presentasion/pages/signup/step/identity-verification/widgets/city_selection.dart';

class LocationSelectionController extends GetxController {
  final AdiminstrativeLocationRepository _AdiminstrativeLocationRepository =
      AdiminstrativeLocationRepository();

  final RxList<AdministrativeDivision> divisions =
      <AdministrativeDivision>[].obs;
  final RxList<AdministrativeDivision> filteredDivisions =
      <AdministrativeDivision>[].obs;
  final RxBool isLoading = false.obs;
  final RxBool searchActive = false.obs;

  // For search functionality
  final TextEditingController searchController = TextEditingController();
  final RxList<AdministrativeDivision> searchResults =
      <AdministrativeDivision>[].obs;

  // Current selection tracking
  Rx<DivisionType> currentDivisionType = DivisionType.province.obs;
  RxString currentParentId = RxString('');

  @override
  void onInit() {
    super.onInit();
    searchController.addListener(_onSearchChanged);
  }

  @override
  void onClose() {
    searchController.removeListener(_onSearchChanged);
    searchController.dispose();
    super.onClose();
  }

  void _onSearchChanged() {
    if (searchController.text.isEmpty && searchActive.value) {
      searchActive.value = false;
      filteredDivisions.value = divisions;
    } else if (searchController.text.isNotEmpty) {
      searchActive.value = true;
    }
  }

  Future<void> loadDivisions(
    DivisionType divisionType,
    String? parentId,
  ) async {
    try {
      isLoading.value = true;
      currentDivisionType.value = divisionType;
      currentParentId.value = parentId ?? '';

      // Load divisions by type and parent
      final result = await _AdiminstrativeLocationRepository.getDivisionsByType(
        divisionType,
        parentId,
      );

      divisions.value = result;
      filteredDivisions.value = result;
    } catch (e) {
      print('Error loading divisions: $e');
      // Show error message if needed
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> updateSearch(String query) async {
    if (query.isEmpty) {
      clearSearch();
      return;
    }

    searchActive.value = true;

    if (query.length < 3) {
      // Only filter current level for short queries
      filteredDivisions.value =
          divisions
              .where(
                (division) =>
                    division.name.toLowerCase().contains(query.toLowerCase()),
              )
              .toList();
    } else {
      // For longer queries, search across all levels
      isLoading.value = true;
      try {
        final results = await _AdiminstrativeLocationRepository.searchLocations(
          query,
        );
        filteredDivisions.value = results;
      } catch (e) {
        print('Error searching locations: $e');
      } finally {
        isLoading.value = false;
      }
    }
  }

  void clearSearch() {
    searchController.clear();
    searchActive.value = false;
    filteredDivisions.value = divisions;
  }

  Future<String> getFullLocationString(AdministrativeDivision division) async {
    return await _AdiminstrativeLocationRepository.getFullLocationString(
      division,
    );
  }

  Future<void> navigateToBreadcrumb(int index, List<String> breadcrumbs) async {
    // Determine the division type based on breadcrumb level
    final DivisionType divisionType = _getDivisionTypeForBreadcrumb(index);

    // Get parent ID if appropriate (might be null for province level)
    String? parentId;
    if (index > 0) {
      // We need to find the parent ID based on the previous breadcrumb
      parentId = await _AdiminstrativeLocationRepository.getIdFromName(
        breadcrumbs[index - 1],
        _getDivisionTypeForBreadcrumb(index - 1),
      );
    }

    // Create shortened breadcrumbs list
    final List<String> updatedBreadcrumbs = breadcrumbs.sublist(0, index + 1);

    // Navigate to the appropriate location selection page
    Get.off(
      () => LocationSelectionPage(
        initialDivisionType: divisionType,
        parentId: parentId,
        breadcrumbs: updatedBreadcrumbs,
      ),
    );
  }

  DivisionType _getDivisionTypeForBreadcrumb(int index) {
    switch (index) {
      case 0:
        return DivisionType.province;
      case 1:
        return DivisionType.regency;
      case 2:
        return DivisionType.district;
      case 3:
        return DivisionType.village;
      default:
        return DivisionType.province;
    }
  }
}
