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';

final CollectionReference professionsCollection =
    FirebaseFirestore.instance.collection('professions');

Future<List<String>> getProfessions() async {
  try {
    DocumentSnapshot<Object?> profession =
        await professionsCollection.doc('professions').get();

    Map<String, dynamic> data = profession.data() as Map<String, dynamic>;

    var professionsList = (data['professions'] as List<dynamic>)
        .map((e) => e.toString())
        .toList();

    return professionsList;
  } catch (e) {
    print('xd $e');
  }

  return [];
}

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

  @override
  State<ProfessionScreen> createState() => _ProfessionScreenState();
}

class _ProfessionScreenState extends State<ProfessionScreen> {
  List<String>? filteredProfessions;
  TextEditingController searchController = TextEditingController();
  final User? user = FirebaseAuth.instance.currentUser;
  List<String>? _professions;
  final uid = AuthenticationRepository.instance.getCurrentUserUid();

  @override
  void initState() {
    super.initState();
    searchController.addListener(() {
      setState(() {
        if (_professions != null) {
          if (searchController.text.isEmpty) {
            filteredProfessions = _professions!;
          } else {
            filteredProfessions = _professions!
                .where((profession) => removeDiacritics(profession)
                    .toLowerCase()
                    .contains(
                        removeDiacritics(searchController.text.toLowerCase())))
                .toList();
          }
        }
      });
    });

    if (_professions == null) {
      getProfessions().then((List<String> element) => setState(() {
            _professions = element;
            filteredProfessions = element;
          }));
    }
  }

  Future<void> updateProfession(String profession) async {
    try {
      await FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({'profesion': profession});

      print('Profesion actualizada correctamente');
    } catch (e) {
      try {
        await FirebaseFirestore.instance
            .collection('users')
            .doc(uid)
            .set({'profesion': profession});
      } catch (e) {
        print('Error al agregar la profesion: $e');
      }

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

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

    return SafeArea(
        child: Scaffold(
      appBar: AppBar(
          backgroundColor: Colors.white,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          iconTheme: const IconThemeData(
            color: Colors.black,
          ),
          title: const Text(
            'Seleccione su profesión',
            style: TextStyle(
              color: Colors.black,
            ),
          )),
      body: Column(
        children: [
          Padding(
            padding: EdgeInsets.only(left: 10, right: 10, top: 10),
            child: TextField(
              controller: searchController,
              decoration: InputDecoration(
                hintText: 'Buscar su profesión',
                prefixIcon: Icon(Icons.assignment_ind_rounded),
              ),
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: professions.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Text(
                    professions[index],
                    style: const TextStyle(
                      fontSize: 18.0,
                      color: Colors.black,
                    ),
                  ),
                  onTap: () {
                    updateProfession(professions[index]);
                    Navigator.pop(context, professions[index]);
                  },
                );
              },
            ),
          ),
        ],
      ),
    ));
  }
}
