import 'package:flutter/material.dart';
import 'package:prosapp_web_app/models/city.dart';
import 'package:prosapp_web_app/services/api_service.dart';

class CitiesProvider extends ChangeNotifier {
  List<City> cities = [];
  bool isLoading = true;
  final _api = ApiService.instance;

  CitiesProvider() {
    getCities();
  }

  getCoordsOfCity(String cityName) {
    for (var city in cities) {
      if (city.cityName == cityName) return city.coordsOfCity;
    }
    return null;
  }

  // Busca una ciudad que coincida con el nombre geocodificado (comparación flexible)
  City? findMatchingCity(String geocodedName) {
    if (geocodedName.isEmpty || cities.isEmpty) return null;
    final normalized = geocodedName.toLowerCase().trim();
    // Intento exacto primero
    for (final c in cities) {
      if (c.cityName.toLowerCase() == normalized) return c;
    }
    // Coincidencia parcial: el nombre geocodificado contiene el nombre de ciudad
    for (final c in cities) {
      final cn = c.cityName.toLowerCase();
      if (normalized.contains(cn) || cn.contains(normalized.split(',').first.trim())) return c;
    }
    return null;
  }

  bool isCityAvailable(String geocodedName) => findMatchingCity(geocodedName) != null;

  getCities() async {
    try {
      // GET /locations/countries returns nested {regions: [{cities: [...]}]}
      final countries = await _api.get('/locations/countries') as List;
      final result = <City>[];
      for (final country in countries) {
        final countryName = country['name'] as String? ?? 'Colombia';
        for (final region in (country['regions'] as List? ?? [])) {
          final regionName = region['name'] as String? ?? '';
          for (final c in (region['cities'] as List? ?? [])) {
            final lat = (c['latitude'] as num?)?.toDouble() ?? 0.0;
            final lng = (c['longitude'] as num?)?.toDouble() ?? 0.0;
            result.add(City(
              cityName: c['name'] as String,
              coordsOfCity: lat != 0.0 ? '$lat,$lng' : '',
              stateOfCity: regionName,
              countryOfCity: countryName,
            ));
          }
        }
      }
      cities = result..sort((a, b) => a.cityName.compareTo(b.cityName));
    } catch (e) {
      print('Error obteniendo ciudades: $e');
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }
}
