import 'package:flutter/material.dart';
import 'package:p_tits_pas/models/parent_model.dart';
import 'package:p_tits_pas/services/user_service.dart';
import 'package:p_tits_pas/widgets/admin/common/admin_parent_edit_modal.dart';
import 'package:p_tits_pas/widgets/admin/common/admin_user_card.dart';
import 'package:p_tits_pas/widgets/admin/common/user_list.dart';

class ParentManagementWidget extends StatefulWidget {
  final String searchQuery;
  final String? statusFilter;

  const ParentManagementWidget({
    super.key,
    required this.searchQuery,
    this.statusFilter,
  });

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

class _ParentManagementWidgetState extends State<ParentManagementWidget> {
  bool _isLoading = false;
  String? _error;
  List<ParentModel> _parents = [];

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

  @override
  void dispose() => super.dispose();

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

  @override
  Widget build(BuildContext context) {
    final query = widget.searchQuery.toLowerCase();
    final filteredParents = _parents.where((p) {
      final matchesName = p.user.fullName.toLowerCase().contains(query) ||
          p.user.email.toLowerCase().contains(query);
      final matchesStatus =
          widget.statusFilter == null || p.user.statut == widget.statusFilter;
      return matchesName && matchesStatus;
    }).toList();

    return UserList(
      isLoading: _isLoading,
      error: _error,
      isEmpty: filteredParents.isEmpty,
      emptyMessage: 'Aucun parent trouvé.',
      itemCount: filteredParents.length,
      itemBuilder: (context, index) {
        final parent = filteredParents[index];
        return AdminUserCard(
          title: parent.user.fullName,
          fallbackIcon: Icons.supervisor_account_outlined,
          avatarUrl: parent.user.photoUrl,
          onCardTap: () => _openParentDetails(parent),
          subtitleLines: [
            parent.user.email,
            'Statut : ${_displayStatus(parent.user.statut)} | Enfants : ${ParentModel.foyerChildrenCount(parent, _parents)}',
          ],
          actions: [
            IconButton(
              icon: const Icon(Icons.edit),
              tooltip: 'Modifier',
              onPressed: () {
                _openParentDetails(parent);
              },
            ),
          ],
        );
      },
    );
  }

  String _displayStatus(String? status) {
    switch (status) {
      case 'actif':
        return 'Actif';
      case 'en_attente':
        return 'En attente';
      case 'suspendu':
        return 'Suspendu';
      case 'refuse':
        return 'Refusé';
      default:
        return 'Inconnu';
    }
  }

  void _openParentDetails(ParentModel parent) {
    showDialog<void>(
      context: context,
      builder: (context) => AdminParentEditModal(
        parent: parent,
        onSaved: _loadParents,
      ),
    );
  }
}
