import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:diacritic/diacritic.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:prosappco/src/authentication/authentication_repository.dart';
import 'package:prosappco/src/components/pop_appbar.dart';

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

  @override
  State<CityScreen> createState() => _CityScreenState();
}

final CollectionReference countriesCollection =
    FirebaseFirestore.instance.collection('countries');

class City {
  String? cityName;
  String? coordsOfCity;
  String? stateOfCity;
  String? countryOfCity;

  City({
    this.cityName,
    this.coordsOfCity,
    this.stateOfCity,
    this.countryOfCity,
  });

  @override
  String toString() {
    return "${cityName ?? ""}, ${coordsOfCity ?? ""}, ${stateOfCity ?? ""}, ${countryOfCity ?? ""}";
  }
}

Future<List<City>> getCountries() async {
  List<City> citys = [];

  try {
    QuerySnapshot countries = await countriesCollection.get();
    for (DocumentSnapshot country in countries.docs) {
      String countryName = country.id;
      Map<String, dynamic> data = country.data() as Map<String, dynamic>;
      Map<String, Map<String, String>> states = {};

      for (var entry in data.entries) {
        String key = entry.key;
        Map<String, String> cityData = Map<String, String>.from(entry.value);
        states[key] = cityData;
      }

      for (var state in states.entries) {
        var citysState = state.value.entries.map((city) => City(
              cityName: city.key,
              coordsOfCity: city.value,
              stateOfCity: state.key,
              countryOfCity: countryName,
            ));

        citys.addAll(citysState);
      }
    }
  } catch (e) {
    print('$e');
  }

  return citys;
}

class _CityScreenState extends State<CityScreen> {
  List<City>? filteredCities;

  TextEditingController searchController = TextEditingController();
  final User? user = FirebaseAuth.instance.currentUser;

  final uid = AuthenticationRepository.instance.getCurrentUserUid();
  List<City>? _cities;

  @override
  void initState() {
    super.initState();
    searchController.addListener(() {
      setState(() {
        if (_cities != null) {
          if (searchController.text.isEmpty) {
            filteredCities = _cities!;
          } else {
            filteredCities = _cities!
                .where((city) => removeDiacritics(city.cityName!)
                    .toLowerCase()
                    .contains(
                        removeDiacritics(searchController.text.toLowerCase())))
                .toList();
          }
        }
      });
    });

    if (_cities == null) {
      getCountries().then((List<City> element) => setState(() {
            _cities = element;
            filteredCities = element;
          }));
    }
  }

  Future<void> updateCity(String cityName, String coordsCity) async {
    try {
      await FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'city': cityName});

      await FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'coordsOfCity': coordsCity});
    } catch (e) {
      try {
        await FirebaseFirestore.instance
            .collection('users')
            .doc(uid)
            .set({'city': cityName});

        await FirebaseFirestore.instance
            .collection('users')
            .doc(uid)
            .set({'coordsOfCity': coordsCity});
      } catch (e) {
        print('Error al agregar la ciudad: $e');
      }

      print('Error al actualizar la ciudad: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    if (filteredCities == null) {
      return const Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF2BA4EC)),
        ),
      );
    }
    var citys = filteredCities!;

    return SafeArea(
      child: Scaffold(
        appBar: PopAppbar(
            onPressed: () {
              Navigator.pop(context);
            },
            label: 'Seleccione su ciudad'),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 10, right: 10, top: 10),
              child: TextField(
                controller: searchController,
                decoration: const InputDecoration(
                  hintText: 'Buscar ciudad',
                  prefixIcon: Icon(Icons.near_me),
                ),
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: citys.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: RichText(
                      text: TextSpan(
                        style: const TextStyle(
                          fontSize: 18.0,
                          color: Colors.black,
                        ),
                        children: [
                          TextSpan(
                            text: '${citys[index].cityName ?? ""}, ',
                            style: const TextStyle(fontWeight: FontWeight.bold),
                          ),
                          TextSpan(
                            text:
                                "${citys[index].stateOfCity ?? ""}, ${citys[index].countryOfCity ?? ""}",
                            style: TextStyle(color: Colors.grey[600]),
                          ),
                        ],
                      ),
                    ),
                    onTap: () {
                      updateCity(citys[index].cityName ?? "",
                          citys[index].coordsOfCity ?? "");
                      Navigator.pop(context, citys[index].cityName ?? "");
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
