import 'package:flutter/material.dart';
import 'package:p_tits_pas/models/parent_model.dart';
import 'package:p_tits_pas/services/user_service.dart';

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

  @override
  State<ParentManagementWidget> createState() => _ParentManagementWidgetState();
}

class _ParentManagementWidgetState extends State<ParentManagementWidget> {
  bool _isLoading = false;
  String? _error;
  List<ParentModel> _parents = [];
  List<ParentModel> _filteredParents = [];
  
  final TextEditingController _searchController = TextEditingController();
  String? _selectedStatus;

  @override
  void initState() {
    super.initState();
    _loadParents();
    _searchController.addListener(_filter);
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadParents() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });
    try {
      final list = await UserService.getParents();
      if (!mounted) return;
      setState(() {
        _parents = list;
        _filter(); // Apply initial filter (if any)
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = e.toString();
        _isLoading = false;
      });
    }
  }

  void _filter() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      _filteredParents = _parents.where((p) {
        final matchesName = p.user.fullName.toLowerCase().contains(query) ||
            p.user.email.toLowerCase().contains(query);
        final matchesStatus = _selectedStatus == null ||
            _selectedStatus == 'Tous' ||
            (p.user.statut?.toLowerCase() == _selectedStatus?.toLowerCase());
        
        // Mapping simple pour le statut affiché vs backend
        // Backend: en_attente, actif, suspendu
        // Dropdown: En attente, Actif, Suspendu
        
        return matchesName && matchesStatus;
      }).toList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSearchSection(),
          const SizedBox(height: 16),
          if (_isLoading)
            const Center(child: CircularProgressIndicator())
          else if (_error != null)
            Center(child: Text('Erreur: $_error', style: const TextStyle(color: Colors.red)))
          else if (_filteredParents.isEmpty)
            const Center(child: Text("Aucun parent trouvé."))
          else
            Expanded(
              child: ListView.builder(
                itemCount: _filteredParents.length,
                itemBuilder: (context, index) {
                  final parent = _filteredParents[index];
                  return Card(
                    margin: const EdgeInsets.symmetric(vertical: 8),
                    child: ListTile(
                      leading: CircleAvatar(
                        backgroundImage: parent.user.photoUrl != null
                            ? NetworkImage(parent.user.photoUrl!)
                            : null,
                        child: parent.user.photoUrl == null
                            ? const Icon(Icons.person)
                            : null,
                      ),
                      title: Text(parent.user.fullName.isNotEmpty
                          ? parent.user.fullName
                          : 'Sans nom'),
                      subtitle: Text(
                        "${parent.user.email}\nStatut : ${parent.user.statut ?? 'Inconnu'} | Enfants : ${parent.childrenCount}",
                      ),
                      isThreeLine: true,
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          IconButton(
                            icon: const Icon(Icons.visibility),
                            tooltip: "Voir dossier",
                            onPressed: () {
                              // TODO: Voir le statut du dossier
                            },
                          ),
                          IconButton(
                            icon: const Icon(Icons.edit),
                            tooltip: "Modifier",
                            onPressed: () {
                              // TODO: Modifier parent
                            },
                          ),
                          IconButton(
                            icon: const Icon(Icons.delete),
                            tooltip: "Supprimer",
                            onPressed: () {
                              // TODO: Supprimer compte
                            },
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildSearchSection() {
    return Wrap(
      spacing: 16,
      runSpacing: 8,
      children: [
        SizedBox(
          width: 220,
          child: TextField(
            controller: _searchController,
            decoration: const InputDecoration(
              labelText: "Nom du parent",
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.search),
            ),
          ),
        ),
        SizedBox(
          width: 220,
          child: DropdownButtonFormField<String>(
            decoration: const InputDecoration(
              labelText: "Statut",
              border: OutlineInputBorder(),
            ),
            value: _selectedStatus,
            items: const [
              DropdownMenuItem(value: null, child: Text("Tous")),
              DropdownMenuItem(value: "actif", child: Text("Actif")),
              DropdownMenuItem(value: "en_attente", child: Text("En attente")),
              DropdownMenuItem(value: "suspendu", child: Text("Suspendu")),
            ],
            onChanged: (value) {
              setState(() {
                _selectedStatus = value;
                _filter();
              });
            },
          ),
        ),
      ],
    );
  }
}
