import 'package:diacritic/diacritic.dart';
import 'package:flutter/material.dart';
import 'package:prosappco/src/components/pop_appbar.dart';
import 'package:prosappco/src/screens/profession.dart';

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

  @override
  State<ServiceTypeScreen> createState() => _ServiceTypeScreenState();
}

class _ServiceTypeScreenState extends State<ServiceTypeScreen> {
  List<String>? filteredProfessions;
  TextEditingController searchController = TextEditingController();
  List<String>? _professions;

  @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;
          }));
    }
  }

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

    return Scaffold(
      appBar: PopAppbar(
          onPressed: () {
            Navigator.pop(context);
          },
          label: 'Tipo de servicio'),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(10),
            child: TextField(
              controller: searchController,
              decoration: const InputDecoration(
                hintText: 'Escribe el tipo de servicio',
                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: () {
                    Navigator.pop(context, professions[index]);
                  },
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
