import 'package:flutter/material.dart';
import 'package:geosector_app/core/data/models/user_model.dart';
import 'package:geosector_app/core/data/models/amicale_model.dart';
import 'package:geosector_app/presentation/widgets/user_form.dart';

class UserFormDialog extends StatefulWidget {
  final UserModel? user;
  final String title;
  final bool readOnly;
  final Function(UserModel, {String? password})? onSubmit; // Modifié pour inclure le mot de passe
  final bool showRoleSelector;
  final List<RoleOption>? availableRoles;
  final bool showActiveCheckbox;
  final bool allowUsernameEdit;
  final AmicaleModel? amicale; // Nouveau paramètre
  final bool isAdmin; // Nouveau paramètre

  const UserFormDialog({
    super.key,
    this.user,
    required this.title,
    this.readOnly = false,
    this.onSubmit,
    this.showRoleSelector = false,
    this.availableRoles,
    this.showActiveCheckbox = false,
    this.allowUsernameEdit = false,
    this.amicale,
    this.isAdmin = false,
  });

  @override
  State<UserFormDialog> createState() => _UserFormDialogState();
}

class RoleOption {
  final int value;
  final String label;
  final String description;

  const RoleOption({
    required this.value,
    required this.label,
    required this.description,
  });
}

class _UserFormDialogState extends State<UserFormDialog> {
  final GlobalKey<UserFormState> _userFormKey = GlobalKey<UserFormState>();
  int? _selectedRole;
  bool? _isActive;

  @override
  void initState() {
    super.initState();
    _selectedRole = widget.user?.role;
    _isActive = widget.user?.isActive ?? true; // Initialiser le statut actif
  }

  void _handleSubmit() async {
    // Utiliser la méthode asynchrone validateAndGetUserAsync du UserForm
    final userData = await _userFormKey.currentState?.validateAndGetUserAsync(context);
    final password = _userFormKey.currentState?.getPassword(); // Récupérer le mot de passe

    if (userData == null) {
      // Afficher une dialog si la validation échoue
      if (context.mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Row(
              children: [
                Icon(Icons.warning_amber_rounded, color: Colors.orange),
                SizedBox(width: 8),
                Text('Formulaire incomplet'),
              ],
            ),
            content: const Text('Veuillez vérifier tous les champs marqués en rouge avant d\'enregistrer'),
            actions: [
              ElevatedButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('OK'),
              ),
            ],
          ),
        );
      }
      return;
    }

    // À ce stade, userData ne peut pas être null
    var finalUser = userData;

    // Ajouter le rôle sélectionné si applicable
    if (widget.showRoleSelector && _selectedRole != null) {
      finalUser = finalUser.copyWith(role: _selectedRole);
    }

    // Ajouter le statut actif si applicable
    if (widget.showActiveCheckbox && _isActive != null) {
      finalUser = finalUser.copyWith(isActive: _isActive);
    }

    if (widget.onSubmit != null) {
      widget.onSubmit!(finalUser, password: password); // Passer le mot de passe
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        width: MediaQuery.of(context).size.width * 0.5,
        constraints: const BoxConstraints(
          maxWidth: 600,
          maxHeight: 700,
        ),
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // Header
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  widget.title,
                  style: theme.textTheme.headlineSmall?.copyWith(
                    fontWeight: FontWeight.bold,
                    color: theme.colorScheme.primary,
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              ],
            ),
            const Divider(),

            // Contenu du formulaire
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Sélecteur de rôle (si activé)
                    if (widget.showRoleSelector && widget.availableRoles != null) ...[
                      Text(
                        'Rôle dans l\'amicale',
                        style: theme.textTheme.titleSmall?.copyWith(
                          fontWeight: FontWeight.w500,
                          color: theme.colorScheme.onSurface,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: widget.availableRoles!.map((role) {
                          return Expanded(
                            child: Row(
                              children: [
                                // TODO: Migrer vers RadioGroup quand disponible (Flutter 4.0+)
                                Radio<int>(
                                  value: role.value,
                                  groupValue: _selectedRole, // ignore: deprecated_member_use
                                  onChanged: widget.readOnly // ignore: deprecated_member_use
                                      ? null
                                      : (value) {
                                          setState(() {
                                            _selectedRole = value;
                                          });
                                        },
                                  activeColor: theme.colorScheme.primary,
                                ),
                                Flexible(
                                  child: GestureDetector(
                                    onTap: widget.readOnly
                                        ? null
                                        : () {
                                            setState(() {
                                              _selectedRole = role.value;
                                            });
                                          },
                                    child: Text(
                                      role.label,
                                      style: theme.textTheme.bodyMedium,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          );
                        }).toList(),
                      ),
                      const SizedBox(height: 16),
                    ],

                    // Checkbox Statut Actif (si activé)
                    if (widget.showActiveCheckbox) ...[
                      Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          border: Border.all(color: theme.colorScheme.outline),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: CheckboxListTile(
                          title: Text(
                            'Compte actif',
                            style: theme.textTheme.titleSmall?.copyWith(
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          subtitle: Text(
                            _isActive == true ? 'Le membre peut se connecter et utiliser l\'application' : 'Le membre ne peut pas se connecter',
                            style: theme.textTheme.bodySmall,
                          ),
                          value: _isActive,
                          onChanged: widget.readOnly
                              ? null
                              : (value) {
                                  setState(() {
                                    _isActive = value ?? true;
                                  });
                                },
                          activeColor: theme.colorScheme.primary,
                          controlAffinity: ListTileControlAffinity.leading,
                        ),
                      ),
                      const SizedBox(height: 16),
                    ],

                    // Formulaire utilisateur avec la clé
                    UserForm(
                      key: _userFormKey,
                      user: widget.user,
                      readOnly: widget.readOnly,
                      allowUsernameEdit: widget.allowUsernameEdit,
                      allowSectNameEdit: widget.isAdmin,  // Toujours éditable pour un admin
                      amicale: widget.amicale, // Passer l'amicale
                      isAdmin: widget.isAdmin, // Passer isAdmin
                      onSubmit: null, // Pas besoin de callback
                    ),

                    // Boutons en bas du scroll
                    const SizedBox(height: 32),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        TextButton(
                          onPressed: () => Navigator.of(context).pop(),
                          child: const Text('Fermer'),
                        ),
                        const SizedBox(width: 16),
                        if (!widget.readOnly)
                          ElevatedButton(
                            onPressed: _handleSubmit,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: theme.colorScheme.primary,
                              foregroundColor: Colors.white,
                            ),
                            child: const Text('Enregistrer'),
                          ),
                      ],
                    ),
                    const SizedBox(height: 16), // Padding supplémentaire pour le confort
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
