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

import 'package:flutter/material.dart';
import '../../../../shared/design_system/tokens/module_colors.dart';
import '../../../../shared/design_system/tokens/color_tokens.dart';
import '../../../../shared/design_system/tokens/app_colors.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/organizations_bloc.dart';
import '../../bloc/organizations_event.dart';
import '../../bloc/org_types_bloc.dart';
import '../../domain/entities/type_reference_entity.dart';
import '../../data/models/organization_model.dart';
import '../../../../core/di/injection_container.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
  String? _selectedTypeCode;
  bool _accepteNouveauxMembres = true;
  late final OrgTypesBloc _orgTypesBloc;
  bool _organisationPublique = true;
  
  @override
  void initState() {
    super.initState();
    _orgTypesBloc = sl<OrgTypesBloc>()..add(const LoadOrgTypes());
  }

  @override
  void dispose() {
    _orgTypesBloc.close();
    _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: ModuleColors.organisations,
                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(
                    'Nouvelle organisation',
                    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 l\'organisation *',
                          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: LIONS, CEADP',
                        ),
                      ),
                      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 dynamique
                      BlocBuilder<OrgTypesBloc, OrgTypesState>(
                        bloc: _orgTypesBloc,
                        builder: (context, orgTypesState) {
                          final types = orgTypesState is OrgTypesLoaded
                              ? orgTypesState.types
                              : orgTypesState is OrgTypeSuccess
                                  ? orgTypesState.types
                                  : <TypeReferenceEntity>[];
                          if (orgTypesState is OrgTypesLoading || orgTypesState is OrgTypesInitial) {
                            return const InputDecorator(
                              decoration: InputDecoration(
                                labelText: 'Type d\'organisation *',
                                border: OutlineInputBorder(),
                                prefixIcon: Icon(Icons.category),
                              ),
                              child: LinearProgressIndicator(),
                            );
                          }
                          final scheme = Theme.of(context).colorScheme;
                          return DropdownButtonFormField<String>(
                            value: types.any((t) => t.code == _selectedTypeCode) ? _selectedTypeCode : null,
                            isExpanded: true,
                            menuMaxHeight: 220,
                            dropdownColor: scheme.surface,
                            style: Theme.of(context).textTheme.bodyLarge?.copyWith(color: scheme.onSurface),
                            decoration: const InputDecoration(
                              labelText: 'Type d\'organisation *',
                              border: OutlineInputBorder(),
                              prefixIcon: Icon(Icons.category),
                            ),
                            items: types.map((type) => DropdownMenuItem<String>(
                              value: type.code,
                              child: Text(
                                type.libelle,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(color: scheme.onSurface),
                              ),
                            )).toList(),
                            onChanged: (value) => setState(() => _selectedTypeCode = value),
                            validator: (value) => value == null ? 'Le type est obligatoire' : null,
                          );
                        },
                      ),
                      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: Theme.of(context).colorScheme.surfaceContainerHighest,
                border: Border(top: BorderSide(color: Theme.of(context).colorScheme.outline)),
              ),
              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: ModuleColors.organisations,
                      foregroundColor: AppColors.onPrimary,
                    ),
                    child: const Text('Créer l\'organisation'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  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: _selectedTypeCode ?? 'ASSOCIATION',
        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('Organisation créée avec succès'),
          backgroundColor: ColorTokens.success,
        ),
      );
    }
  }
}

