/// Dialogue de création d'organisation (mutuelle)
/// Formulaire complet pour créer une nouvelle mutuelle
library create_organisation_dialog;

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/organizations_bloc.dart';
import '../../bloc/organizations_event.dart';
import '../../data/models/organization_model.dart';

/// Dialogue de création d'organisation
class CreateOrganizationDialog extends StatefulWidget {
  const CreateOrganizationDialog({super.key});

  @override
  State<CreateOrganizationDialog> createState() => _CreateOrganizationDialogState();
}

class _CreateOrganizationDialogState extends State<CreateOrganizationDialog> {
  final _formKey = GlobalKey<FormState>();
  
  // Contrôleurs de texte
  final _nomController = TextEditingController();
  final _nomCourtController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _emailController = TextEditingController();
  final _telephoneController = TextEditingController();
  final _adresseController = TextEditingController();
  final _villeController = TextEditingController();
  final _codePostalController = TextEditingController();
  final _regionController = TextEditingController();
  final _paysController = TextEditingController();
  final _siteWebController = TextEditingController();
  final _objectifsController = TextEditingController();
  
  // Valeurs sélectionnées
  TypeOrganization _selectedType = TypeOrganization.association;
  bool _accepteNouveauxMembres = true;
  bool _organisationPublique = true;
  
  @override
  void dispose() {
    _nomController.dispose();
    _nomCourtController.dispose();
    _descriptionController.dispose();
    _emailController.dispose();
    _telephoneController.dispose();
    _adresseController.dispose();
    _villeController.dispose();
    _codePostalController.dispose();
    _regionController.dispose();
    _paysController.dispose();
    _siteWebController.dispose();
    _objectifsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        width: MediaQuery.of(context).size.width * 0.9,
        constraints: const BoxConstraints(maxHeight: 600),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // En-tête
            Container(
              padding: const EdgeInsets.all(16),
              decoration: const BoxDecoration(
                color: Color(0xFF8B5CF6),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(4),
                  topRight: Radius.circular(4),
                ),
              ),
              child: Row(
                children: [
                  const Icon(Icons.business, color: Colors.white),
                  const SizedBox(width: 12),
                  const Text(
                    'Créer une mutuelle',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const Spacer(),
                  IconButton(
                    icon: const Icon(Icons.close, color: Colors.white),
                    onPressed: () => Navigator.pop(context),
                  ),
                ],
              ),
            ),
            
            // Formulaire
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Informations de base
                      _buildSectionTitle('Informations de base'),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _nomController,
                        decoration: const InputDecoration(
                          labelText: 'Nom de la mutuelle *',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.business),
                        ),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'Le nom est obligatoire';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _nomCourtController,
                        decoration: const InputDecoration(
                          labelText: 'Nom court / Sigle',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.short_text),
                          hintText: 'Ex: MUTEC, MUPROCI',
                        ),
                      ),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _descriptionController,
                        decoration: const InputDecoration(
                          labelText: 'Description',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.description),
                        ),
                        maxLines: 3,
                      ),
                      const SizedBox(height: 12),
                      
                      // Type d'organisation
                      DropdownButtonFormField<TypeOrganization>(
                        value: _selectedType,
                        decoration: const InputDecoration(
                          labelText: 'Type d\'organisation *',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.category),
                        ),
                        items: TypeOrganization.values.map((type) {
                          return DropdownMenuItem(
                            value: type,
                            child: Text(type.displayName),
                          );
                        }).toList(),
                        onChanged: (value) {
                          setState(() {
                            _selectedType = value!;
                          });
                        },
                      ),
                      const SizedBox(height: 16),
                      
                      // Contact
                      _buildSectionTitle('Contact'),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _emailController,
                        decoration: const InputDecoration(
                          labelText: 'Email *',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.email),
                        ),
                        keyboardType: TextInputType.emailAddress,
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return 'L\'email est obligatoire';
                          }
                          if (!value.contains('@')) {
                            return 'Email invalide';
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _telephoneController,
                        decoration: const InputDecoration(
                          labelText: 'Téléphone',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.phone),
                        ),
                        keyboardType: TextInputType.phone,
                      ),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _siteWebController,
                        decoration: const InputDecoration(
                          labelText: 'Site web',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.language),
                          hintText: 'https://',
                        ),
                        keyboardType: TextInputType.url,
                      ),
                      const SizedBox(height: 16),
                      
                      // Adresse
                      _buildSectionTitle('Adresse'),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _adresseController,
                        decoration: const InputDecoration(
                          labelText: 'Adresse',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.home),
                        ),
                        maxLines: 2,
                      ),
                      const SizedBox(height: 12),
                      
                      Row(
                        children: [
                          Expanded(
                            child: TextFormField(
                              controller: _villeController,
                              decoration: const InputDecoration(
                                labelText: 'Ville',
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: TextFormField(
                              controller: _codePostalController,
                              decoration: const InputDecoration(
                                labelText: 'Code postal',
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _regionController,
                        decoration: const InputDecoration(
                          labelText: 'Région',
                          border: OutlineInputBorder(),
                        ),
                      ),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _paysController,
                        decoration: const InputDecoration(
                          labelText: 'Pays',
                          border: OutlineInputBorder(),
                        ),
                      ),
                      const SizedBox(height: 16),
                      
                      // Objectifs
                      _buildSectionTitle('Objectifs et mission'),
                      const SizedBox(height: 12),
                      
                      TextFormField(
                        controller: _objectifsController,
                        decoration: const InputDecoration(
                          labelText: 'Objectifs',
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.flag),
                        ),
                        maxLines: 3,
                      ),
                      const SizedBox(height: 16),
                      
                      // Paramètres
                      _buildSectionTitle('Paramètres'),
                      const SizedBox(height: 12),
                      
                      SwitchListTile(
                        title: const Text('Accepte de nouveaux membres'),
                        subtitle: const Text('Permet l\'adhésion de nouveaux membres'),
                        value: _accepteNouveauxMembres,
                        onChanged: (value) {
                          setState(() {
                            _accepteNouveauxMembres = value;
                          });
                        },
                      ),
                      
                      SwitchListTile(
                        title: const Text('Organisation publique'),
                        subtitle: const Text('Visible dans l\'annuaire public'),
                        value: _organisationPublique,
                        onChanged: (value) {
                          setState(() {
                            _organisationPublique = value;
                          });
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // Boutons d'action
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                border: Border(top: BorderSide(color: Colors.grey[300]!)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () => Navigator.pop(context),
                    child: const Text('Annuler'),
                  ),
                  const SizedBox(width: 12),
                  ElevatedButton(
                    onPressed: _submitForm,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF8B5CF6),
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('Créer la mutuelle'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
        color: Color(0xFF8B5CF6),
      ),
    );
  }

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      // Créer le modèle d'organisation
      final organisation = OrganizationModel(
        nom: _nomController.text,
        nomCourt: _nomCourtController.text.isNotEmpty ? _nomCourtController.text : null,
        description: _descriptionController.text.isNotEmpty ? _descriptionController.text : null,
        email: _emailController.text,
        telephone: _telephoneController.text.isNotEmpty ? _telephoneController.text : null,
        adresse: _adresseController.text.isNotEmpty ? _adresseController.text : null,
        ville: _villeController.text.isNotEmpty ? _villeController.text : null,
        codePostal: _codePostalController.text.isNotEmpty ? _codePostalController.text : null,
        region: _regionController.text.isNotEmpty ? _regionController.text : null,
        pays: _paysController.text.isNotEmpty ? _paysController.text : null,
        siteWeb: _siteWebController.text.isNotEmpty ? _siteWebController.text : null,
        objectifs: _objectifsController.text.isNotEmpty ? _objectifsController.text : null,
        typeOrganisation: _selectedType,
        statut: StatutOrganization.active,
        accepteNouveauxMembres: _accepteNouveauxMembres,
        organisationPublique: _organisationPublique,
      );

      // Envoyer l'événement au BLoC
      context.read<OrganizationsBloc>().add(CreateOrganization(organisation));
      
      // Fermer le dialogue
      Navigator.pop(context);
      
      // Afficher un message de succès
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Mutuelle créée avec succès'),
          backgroundColor: Colors.green,
        ),
      );
    }
  }
}

