import 'package:flutter/material.dart';
import 'package:p_tits_pas/models/user.dart';
import 'package:p_tits_pas/screens/administrateurs/creation/gestionnaires_create.dart';
import 'package:p_tits_pas/services/user_service.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 GestionnaireManagementWidget extends StatefulWidget {
  final String searchQuery;

  const GestionnaireManagementWidget({
    Key? key,
    required this.searchQuery,
  }) : super(key: key);

  @override
  State<GestionnaireManagementWidget> createState() =>
      _GestionnaireManagementWidgetState();
}

class _GestionnaireManagementWidgetState
    extends State<GestionnaireManagementWidget> {
  bool _isLoading = false;
  String? _error;
  List<AppUser> _gestionnaires = [];

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

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

  Future<void> _loadGestionnaires() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });
    try {
      final gestionnaires = await UserService.getGestionnaires();
      if (!mounted) return;
      setState(() {
        _gestionnaires = gestionnaires;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = e.toString();
        _isLoading = false;
      });
    }
  }

  Future<void> _openGestionnaireEditDialog(AppUser user) async {
    final changed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (dialogContext) {
        return AdminUserFormDialog(initialUser: user);
      },
    );
    if (changed == true) {
      await _loadGestionnaires();
    }
  }

  @override
  Widget build(BuildContext context) {
    final query = widget.searchQuery.toLowerCase();
    final filteredGestionnaires = _gestionnaires.where((u) {
      final name = u.fullName.toLowerCase();
      final email = u.email.toLowerCase();
      return name.contains(query) || email.contains(query);
    }).toList();

    return UserList(
      isLoading: _isLoading,
      error: _error,
      isEmpty: filteredGestionnaires.isEmpty,
      emptyMessage: 'Aucun gestionnaire trouvé.',
      itemCount: filteredGestionnaires.length,
      itemBuilder: (context, index) {
        final user = filteredGestionnaires[index];
        return AdminUserCard(
          title: user.fullName,
          fallbackIcon: Icons.assignment_ind_outlined,
          avatarUrl: user.photoUrl,
          onCardTap: () => _openGestionnaireEditDialog(user),
          subtitleLines: [
            user.email,
            'Statut : ${user.statut ?? 'Inconnu'}',
            'Relais : ${user.relaisNom ?? 'Non rattaché'}',
          ],
          actions: [
            IconButton(
              icon: const Icon(Icons.edit),
              tooltip: 'Modifier',
              onPressed: () {
                _openGestionnaireEditDialog(user);
              },
            ),
          ],
        );
      },
    );
  }
}
