import 'package:flutter/material.dart';
import 'package:em2rp/models/user_model.dart';
import 'package:em2rp/views/widgets/image/profile_picture.dart';

class UserMultiSelectWidget extends StatelessWidget {
  final List<UserModel> allUsers;
  final List<String> selectedUserIds;
  final ValueChanged<List<String>> onChanged;
  final bool isLoading;

  const UserMultiSelectWidget({
    super.key,
    required this.allUsers,
    required this.selectedUserIds,
    required this.onChanged,
    this.isLoading = false,
  });

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return const Center(
        child:
            SizedBox(width: 32, height: 32, child: CircularProgressIndicator()),
      );
    }
    return _UserMultiSelect(
      allUsers: allUsers,
      selectedUserIds: selectedUserIds,
      onChanged: onChanged,
    );
  }
}

class _UserMultiSelect extends StatefulWidget {
  final List<UserModel> allUsers;
  final List<String> selectedUserIds;
  final ValueChanged<List<String>> onChanged;

  const _UserMultiSelect({
    required this.allUsers,
    required this.selectedUserIds,
    required this.onChanged,
  });

  @override
  State<_UserMultiSelect> createState() => _UserMultiSelectState();
}

class _UserMultiSelectState extends State<_UserMultiSelect> {
  void _openUserPicker() async {
    final result = await showDialog<List<String>>(
      context: context,
      builder: (context) => _UserPickerDialog(
        allUsers: widget.allUsers,
        initiallySelected: widget.selectedUserIds,
      ),
    );
    if (result != null) {
      widget.onChanged(result);
    }
  }

  @override
  Widget build(BuildContext context) {
    final selectedUsers = widget.allUsers
        .where((u) => widget.selectedUserIds.contains(u.uid))
        .toList();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        UserChipsList(
          users: selectedUsers,
          selectedUserIds: widget.selectedUserIds,
          showRemove: true,
          onRemove: (uid) {
            final newList = List<String>.from(widget.selectedUserIds)
              ..remove(uid);
            widget.onChanged(newList);
          },
        ),
        const SizedBox(height: 16),
        ElevatedButton.icon(
          icon: const Icon(Icons.add),
          label: const Text('Ajouter'),
          onPressed: _openUserPicker,
        ),
      ],
    );
  }
}

class _UserPickerDialog extends StatefulWidget {
  final List<UserModel> allUsers;
  final List<String> initiallySelected;
  const _UserPickerDialog({
    required this.allUsers,
    required this.initiallySelected,
  });

  @override
  State<_UserPickerDialog> createState() => _UserPickerDialogState();
}

class _UserPickerDialogState extends State<_UserPickerDialog> {
  String _search = '';
  late List<String> _selected;

  @override
  void initState() {
    super.initState();
    _selected = List<String>.from(widget.initiallySelected);
  }

  @override
  Widget build(BuildContext context) {
    final filteredUsers = widget.allUsers.where((u) {
      final query = _search.toLowerCase();
      return ('${u.firstName} ${u.lastName}').toLowerCase().contains(query);
    }).toList();
    return AlertDialog(
      title: const Text('Ajouter du personnel'),
      content: SizedBox(
        width: 400,
        height: 400,
        child: Column(
          children: [
            TextField(
              decoration: const InputDecoration(
                labelText: 'Rechercher',
                prefixIcon: Icon(Icons.search),
              ),
              onChanged: (v) => setState(() => _search = v),
            ),
            const SizedBox(height: 12),
            Expanded(
              child: filteredUsers.isEmpty
                  ? const Center(child: Text('Aucun utilisateur trouvé'))
                  : ListView.builder(
                      itemCount: filteredUsers.length,
                      itemBuilder: (context, i) {
                        final user = filteredUsers[i];
                        final isChecked = _selected.contains(user.uid);
                        return CheckboxListTile(
                          value: isChecked,
                          onChanged: (checked) {
                            setState(() {
                              if (checked == true) {
                                _selected.add(user.uid);
                              } else {
                                _selected.remove(user.uid);
                              }
                            });
                          },
                          title: Text('${user.firstName} ${user.lastName}'),
                          subtitle: Text(user.email),
                          secondary: ProfilePictureWidget(
                              userId: user.uid, radius: 20),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Annuler'),
        ),
        ElevatedButton(
          onPressed: () => Navigator.pop(context, _selected),
          child: const Text('Ajouter'),
        ),
      ],
    );
  }
}

class UserChipsList extends StatelessWidget {
  final List<UserModel> users;
  final List<String> selectedUserIds;
  final ValueChanged<String>? onRemove;
  final bool showRemove;
  final double avatarRadius;
  const UserChipsList({
    super.key,
    required this.users,
    this.selectedUserIds = const [],
    this.onRemove,
    this.showRemove = false,
    this.avatarRadius = 28,
  });

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 12,
      runSpacing: 12,
      children: users
          .map((user) => Chip(
                avatar: ProfilePictureWidget(
                  userId: user.uid,
                  radius: avatarRadius,
                  profilePhotoUrl: user.profilePhotoUrl, // Passer l'URL directement
                ),
                label: Text('${user.firstName} ${user.lastName}',
                    style: const TextStyle(fontSize: 16)),
                labelPadding: const EdgeInsets.symmetric(horizontal: 8),
                deleteIcon:
                    showRemove ? const Icon(Icons.close, size: 20) : null,
                onDeleted: showRemove && onRemove != null
                    ? () => onRemove!(user.uid)
                    : null,
                backgroundColor: Colors.grey[200],
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              ))
          .toList(),
    );
  }
}
