import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:em2rp/models/user_model.dart';
import 'package:em2rp/providers/users_provider.dart';
import 'package:em2rp/utils/colors.dart';

/// Widget de filtre par utilisateur pour le calendrier
/// Affiche un dropdown permettant de filtrer les événements par utilisateur
class UserFilterDropdown extends StatefulWidget {
  final String? selectedUserId;
  final ValueChanged<String?> onUserSelected;

  const UserFilterDropdown({
    super.key,
    required this.selectedUserId,
    required this.onUserSelected,
  });

  @override
  State<UserFilterDropdown> createState() => _UserFilterDropdownState();
}

class _UserFilterDropdownState extends State<UserFilterDropdown> {
  List<UserModel> _users = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    // Charger après le premier frame pour éviter setState pendant build
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        _loadUsers();
      }
    });
  }

  Future<void> _loadUsers() async {
    if (!mounted) return;

    final usersProvider = Provider.of<UsersProvider>(context, listen: false);

    // Ne pas appeler fetchUsers si les utilisateurs sont déjà chargés
    if (usersProvider.users.isEmpty) {
      await usersProvider.fetchUsers();
    }

    if (!mounted) return;

    setState(() {
      _users = usersProvider.users;
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return const SizedBox(
        width: 200,
        child: Center(
          child: SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(strokeWidth: 2),
          ),
        ),
      );
    }

    return Container(
      width: 250,
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String?>(
          value: widget.selectedUserId,
          hint: const Row(
            children: [
              Icon(Icons.filter_list, size: 18, color: Colors.grey),
              SizedBox(width: 8),
              Text('Tous les utilisateurs', style: TextStyle(fontSize: 14)),
            ],
          ),
          isExpanded: true,
          icon: const Icon(Icons.arrow_drop_down, size: 24),
          style: const TextStyle(fontSize: 14, color: Colors.black87),
          onChanged: widget.onUserSelected,
          items: [
            // Option "Tous les utilisateurs"
            const DropdownMenuItem<String?>(
              value: null,
              child: Row(
                children: [
                  Icon(Icons.people, size: 18, color: AppColors.rouge),
                  SizedBox(width: 8),
                  Text('Tous les utilisateurs', style: TextStyle(fontWeight: FontWeight.bold)),
                ],
              ),
            ),
            // Liste des utilisateurs
            ..._users.map((user) {
              return DropdownMenuItem<String?>(
                value: user.uid,
                child: Row(
                  children: [
                    CircleAvatar(
                      radius: 12,
                      backgroundImage: user.profilePhotoUrl.isNotEmpty
                          ? NetworkImage(user.profilePhotoUrl)
                          : null,
                      child: user.profilePhotoUrl.isEmpty
                          ? Text(
                              user.firstName.isNotEmpty
                                  ? user.firstName[0].toUpperCase()
                                  : '?',
                              style: const TextStyle(fontSize: 10),
                            )
                          : null,
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        '${user.firstName} ${user.lastName}',
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              );
            }),
          ],
        ),
      ),
    );
  }
}

