/// Page de création d'une nouvelle organisation
/// Respecte strictement le design system établi dans l'application
library create_organisation_page;

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

/// Page de création d'organisation avec design system cohérent
class CreateOrganizationPage extends StatefulWidget {
  const CreateOrganizationPage({super.key});

  @override
  State<CreateOrganizationPage> createState() => _CreateOrganizationPageState();
}

class _CreateOrganizationPageState extends State<CreateOrganizationPage> {
  final _formKey = GlobalKey<FormState>();
  final _nomController = TextEditingController();
  final _nomCourtController = TextEditingController();
  final _descriptionController = TextEditingController();
  final _emailController = TextEditingController();
  final _telephoneController = TextEditingController();
  final _siteWebController = TextEditingController();
  final _adresseController = TextEditingController();
  final _villeController = TextEditingController();
  final _regionController = TextEditingController();
  final _paysController = TextEditingController();

  TypeOrganization _selectedType = TypeOrganization.association;
  StatutOrganization _selectedStatut = StatutOrganization.active;

  @override
  void dispose() {
    _nomController.dispose();
    _nomCourtController.dispose();
    _descriptionController.dispose();
    _emailController.dispose();
    _telephoneController.dispose();
    _siteWebController.dispose();
    _adresseController.dispose();
    _villeController.dispose();
    _regionController.dispose();
    _paysController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA), // Background cohérent
      appBar: AppBar(
        backgroundColor: const Color(0xFF6C5CE7),
        foregroundColor: Colors.white,
        title: const Text('Nouvelle Organisation'),
        elevation: 0,
        actions: [
          TextButton(
            onPressed: _isFormValid() ? _saveOrganisation : null,
            child: const Text(
              'Enregistrer',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
      body: BlocListener<OrganizationsBloc, OrganizationsState>(
        listener: (context, state) {
          if (state is OrganizationCreated) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('Organisation créée avec succès'),
                backgroundColor: Color(0xFF10B981),
              ),
            );
            Navigator.of(context).pop(true); // Retour avec succès
          } else if (state is OrganizationsError) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.message),
                backgroundColor: Colors.red,
              ),
            );
          }
        },
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(12), // SpacingTokens cohérent
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildBasicInfoCard(),
                const SizedBox(height: 16),
                _buildContactCard(),
                const SizedBox(height: 16),
                _buildLocationCard(),
                const SizedBox(height: 16),
                _buildConfigurationCard(),
                const SizedBox(height: 24),
                _buildActionButtons(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// Carte des informations de base
  Widget _buildBasicInfoCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8), // RadiusTokens cohérent
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Informations de base',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _nomController,
            decoration: const InputDecoration(
              labelText: 'Nom de l\'organisation *',
              hintText: 'Ex: Association des Développeurs',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.business),
            ),
            validator: (value) {
              if (value == null || value.trim().isEmpty) {
                return 'Le nom est obligatoire';
              }
              if (value.trim().length < 3) {
                return 'Le nom doit contenir au moins 3 caractères';
              }
              return null;
            },
            onChanged: (_) => setState(() {}),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _nomCourtController,
            decoration: const InputDecoration(
              labelText: 'Nom court (optionnel)',
              hintText: 'Ex: AsDev',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.short_text),
            ),
            validator: (value) {
              if (value != null && value.trim().isNotEmpty && value.trim().length < 2) {
                return 'Le nom court doit contenir au moins 2 caractères';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          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: Row(
                  children: [
                    Text(type.icon, style: const TextStyle(fontSize: 16)),
                    const SizedBox(width: 8),
                    Text(type.displayName),
                  ],
                ),
              );
            }).toList(),
            onChanged: (value) {
              if (value != null) {
                setState(() {
                  _selectedType = value;
                });
              }
            },
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _descriptionController,
            decoration: const InputDecoration(
              labelText: 'Description (optionnel)',
              hintText: 'Décrivez brièvement l\'organisation...',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.description),
            ),
            maxLines: 3,
            validator: (value) {
              if (value != null && value.trim().isNotEmpty && value.trim().length < 10) {
                return 'La description doit contenir au moins 10 caractères';
              }
              return null;
            },
          ),
        ],
      ),
    );
  }

  /// Carte des informations de contact
  Widget _buildContactCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Contact',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _emailController,
            decoration: const InputDecoration(
              labelText: 'Email (optionnel)',
              hintText: 'contact@organisation.com',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.email),
            ),
            keyboardType: TextInputType.emailAddress,
            validator: (value) {
              if (value != null && value.trim().isNotEmpty) {
                final emailRegex = RegExp(r'^[^@]+@[^@]+\.[^@]+$');
                if (!emailRegex.hasMatch(value.trim())) {
                  return 'Format d\'email invalide';
                }
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _telephoneController,
            decoration: const InputDecoration(
              labelText: 'Téléphone (optionnel)',
              hintText: '+225 XX XX XX XX XX',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.phone),
            ),
            keyboardType: TextInputType.phone,
            validator: (value) {
              if (value != null && value.trim().isNotEmpty && value.trim().length < 8) {
                return 'Numéro de téléphone invalide';
              }
              return null;
            },
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _siteWebController,
            decoration: const InputDecoration(
              labelText: 'Site web (optionnel)',
              hintText: 'https://www.organisation.com',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.web),
            ),
            keyboardType: TextInputType.url,
            validator: (value) {
              if (value != null && value.trim().isNotEmpty) {
                final urlRegex = RegExp(r'^https?://[^\s]+$');
                if (!urlRegex.hasMatch(value.trim())) {
                  return 'Format d\'URL invalide (doit commencer par http:// ou https://)';
                }
              }
              return null;
            },
          ),
        ],
      ),
    );
  }

  /// Carte de localisation
  Widget _buildLocationCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Localisation',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _adresseController,
            decoration: const InputDecoration(
              labelText: 'Adresse (optionnel)',
              hintText: 'Rue, quartier...',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.location_on),
            ),
            maxLines: 2,
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: TextFormField(
                  controller: _villeController,
                  decoration: const InputDecoration(
                    labelText: 'Ville',
                    hintText: 'Abidjan',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.location_city),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: TextFormField(
                  controller: _regionController,
                  decoration: const InputDecoration(
                    labelText: 'Région',
                    hintText: 'Lagunes',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.map),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _paysController,
            decoration: const InputDecoration(
              labelText: 'Pays',
              hintText: 'Côte d\'Ivoire',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.flag),
            ),
          ),
        ],
      ),
    );
  }

  /// Carte de configuration
  Widget _buildConfigurationCard() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Configuration',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 16),
          DropdownButtonFormField<StatutOrganization>(
            value: _selectedStatut,
            decoration: const InputDecoration(
              labelText: 'Statut initial *',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.toggle_on),
            ),
            items: StatutOrganization.values.map((statut) {
              final color = Color(int.parse(statut.color.substring(1), radix: 16) + 0xFF000000);
              return DropdownMenuItem(
                value: statut,
                child: Row(
                  children: [
                    Container(
                      width: 12,
                      height: 12,
                      decoration: BoxDecoration(
                        color: color,
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(statut.displayName),
                  ],
                ),
              );
            }).toList(),
            onChanged: (value) {
              if (value != null) {
                setState(() {
                  _selectedStatut = value;
                });
              }
            },
          ),
        ],
      ),
    );
  }

  /// Boutons d'action
  Widget _buildActionButtons() {
    return Column(
      children: [
        SizedBox(
          width: double.infinity,
          child: ElevatedButton.icon(
            onPressed: _isFormValid() ? _saveOrganisation : null,
            icon: const Icon(Icons.save),
            label: const Text('Créer l\'organisation'),
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF6C5CE7),
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 16),
              textStyle: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
        const SizedBox(height: 12),
        SizedBox(
          width: double.infinity,
          child: OutlinedButton.icon(
            onPressed: () => Navigator.of(context).pop(),
            icon: const Icon(Icons.cancel),
            label: const Text('Annuler'),
            style: OutlinedButton.styleFrom(
              foregroundColor: const Color(0xFF6B7280),
              padding: const EdgeInsets.symmetric(vertical: 16),
              textStyle: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// Vérifie si le formulaire est valide
  bool _isFormValid() {
    return _nomController.text.trim().isNotEmpty;
  }

  /// Sauvegarde l'organisation
  void _saveOrganisation() {
    if (_formKey.currentState?.validate() ?? false) {
      final organisation = OrganizationModel(
        nom: _nomController.text.trim(),
        nomCourt: _nomCourtController.text.trim().isEmpty ? null : _nomCourtController.text.trim(),
        description: _descriptionController.text.trim().isEmpty ? null : _descriptionController.text.trim(),
        typeOrganisation: _selectedType,
        statut: _selectedStatut,
        email: _emailController.text.trim().isEmpty ? null : _emailController.text.trim(),
        telephone: _telephoneController.text.trim().isEmpty ? null : _telephoneController.text.trim(),
        siteWeb: _siteWebController.text.trim().isEmpty ? null : _siteWebController.text.trim(),
        adresse: _adresseController.text.trim().isEmpty ? null : _adresseController.text.trim(),
        ville: _villeController.text.trim().isEmpty ? null : _villeController.text.trim(),
        region: _regionController.text.trim().isEmpty ? null : _regionController.text.trim(),
        pays: _paysController.text.trim().isEmpty ? null : _paysController.text.trim(),
        dateCreation: DateTime.now(),
        nombreMembres: 0,
      );

      context.read<OrganizationsBloc>().add(CreateOrganization(organisation));
    }
  }
}
