/// Page d'édition d'une organisation existante
/// Respecte strictement le design system établi dans l'application
library edit_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 d'édition d'organisation avec design system cohérent
class EditOrganizationPage extends StatefulWidget {
  final OrganizationModel organization;

  const EditOrganizationPage({
    super.key,
    required this.organization,
  });

  @override
  State<EditOrganizationPage> createState() => _EditOrganizationPageState();
}

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

  late TypeOrganization _selectedType;
  late StatutOrganization _selectedStatut;

  @override
  void initState() {
    super.initState();
    // Initialiser les contrôleurs avec les valeurs existantes
    _nomController = TextEditingController(text: widget.organization.nom);
    _nomCourtController = TextEditingController(text: widget.organization.nomCourt ?? '');
    _descriptionController = TextEditingController(text: widget.organization.description ?? '');
    _emailController = TextEditingController(text: widget.organization.email ?? '');
    _telephoneController = TextEditingController(text: widget.organization.telephone ?? '');
    _siteWebController = TextEditingController(text: widget.organization.siteWeb ?? '');
    _adresseController = TextEditingController(text: widget.organization.adresse ?? '');
    _villeController = TextEditingController(text: widget.organization.ville ?? '');
    _regionController = TextEditingController(text: widget.organization.region ?? '');
    _paysController = TextEditingController(text: widget.organization.pays ?? '');

    _selectedType = widget.organization.typeOrganisation;
    _selectedStatut = widget.organization.statut;
  }

  @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('Modifier Organisation'),
        elevation: 0,
        actions: [
          TextButton(
            onPressed: _hasChanges() ? _saveChanges : null,
            child: const Text(
              'Enregistrer',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
      body: BlocListener<OrganizationsBloc, OrganizationsState>(
        listener: (context, state) {
          if (state is OrganizationUpdated) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('Organisation modifié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: 16),
                _buildMetadataCard(),
                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 *',
              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)',
              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;
            },
            onChanged: (_) => setState(() {}),
          ),
          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)',
              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;
            },
            onChanged: (_) => setState(() {}),
          ),
        ],
      ),
    );
  }

  /// 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)',
              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;
            },
            onChanged: (_) => setState(() {}),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _telephoneController,
            decoration: const InputDecoration(
              labelText: 'Téléphone (optionnel)',
              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;
            },
            onChanged: (_) => setState(() {}),
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _siteWebController,
            decoration: const InputDecoration(
              labelText: 'Site web (optionnel)',
              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;
            },
            onChanged: (_) => setState(() {}),
          ),
        ],
      ),
    );
  }

  /// 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)',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.location_on),
            ),
            maxLines: 2,
            onChanged: (_) => setState(() {}),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: TextFormField(
                  controller: _villeController,
                  decoration: const InputDecoration(
                    labelText: 'Ville',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.location_city),
                  ),
                  onChanged: (_) => setState(() {}),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: TextFormField(
                  controller: _regionController,
                  decoration: const InputDecoration(
                    labelText: 'Région',
                    border: OutlineInputBorder(),
                    prefixIcon: Icon(Icons.map),
                  ),
                  onChanged: (_) => setState(() {}),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _paysController,
            decoration: const InputDecoration(
              labelText: 'Pays',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.flag),
            ),
            onChanged: (_) => setState(() {}),
          ),
        ],
      ),
    );
  }

  /// 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 *',
              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;
                });
              }
            },
          ),
        ],
      ),
    );
  }

  /// Carte des métadonnées (lecture seule)
  Widget _buildMetadataCard() {
    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(
            'Informations système',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 16),
          _buildReadOnlyField(
            icon: Icons.fingerprint,
            label: 'ID',
            value: widget.organization.id ?? 'Non défini',
          ),
          const SizedBox(height: 12),
          _buildReadOnlyField(
            icon: Icons.calendar_today,
            label: 'Date de création',
            value: _formatDate(widget.organization.dateCreation),
          ),
          const SizedBox(height: 12),
          _buildReadOnlyField(
            icon: Icons.people,
            label: 'Nombre de membres',
            value: widget.organization.nombreMembres.toString(),
          ),
          if (widget.organization.ancienneteAnnees > 0) ...[
            const SizedBox(height: 12),
            _buildReadOnlyField(
              icon: Icons.access_time,
              label: 'Ancienneté',
              value: '${widget.organization.ancienneteAnnees} ans',
            ),
          ],
        ],
      ),
    );
  }

  /// Champ en lecture seule
  Widget _buildReadOnlyField({
    required IconData icon,
    required String label,
    required String value,
  }) {
    return Row(
      children: [
        Icon(
          icon,
          size: 20,
          color: const Color(0xFF6B7280),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                label,
                style: const TextStyle(
                  fontSize: 12,
                  color: Color(0xFF6B7280),
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 2),
              Text(
                value,
                style: const TextStyle(
                  fontSize: 14,
                  color: Color(0xFF374151),
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// Boutons d'action
  Widget _buildActionButtons() {
    return Column(
      children: [
        SizedBox(
          width: double.infinity,
          child: ElevatedButton.icon(
            onPressed: _hasChanges() ? _saveChanges : null,
            icon: const Icon(Icons.save),
            label: const Text('Enregistrer les modifications'),
            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: () => _showDiscardDialog(),
            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 s'il y a des changements
  bool _hasChanges() {
    return _nomController.text.trim() != widget.organization.nom ||
        _nomCourtController.text.trim() != (widget.organization.nomCourt ?? '') ||
        _descriptionController.text.trim() != (widget.organization.description ?? '') ||
        _emailController.text.trim() != (widget.organization.email ?? '') ||
        _telephoneController.text.trim() != (widget.organization.telephone ?? '') ||
        _siteWebController.text.trim() != (widget.organization.siteWeb ?? '') ||
        _adresseController.text.trim() != (widget.organization.adresse ?? '') ||
        _villeController.text.trim() != (widget.organization.ville ?? '') ||
        _regionController.text.trim() != (widget.organization.region ?? '') ||
        _paysController.text.trim() != (widget.organization.pays ?? '') ||
        _selectedType != widget.organization.typeOrganisation ||
        _selectedStatut != widget.organization.statut;
  }

  /// Sauvegarde les modifications
  void _saveChanges() {
    if (_formKey.currentState?.validate() ?? false) {
      final updatedOrganisation = widget.organization.copyWith(
        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(),
      );

      if (widget.organization.id != null) {
        context.read<OrganizationsBloc>().add(
          UpdateOrganization(widget.organization.id!, updatedOrganisation),
        );
      }
    }
  }

  /// Affiche le dialog de confirmation d'annulation
  void _showDiscardDialog() {
    if (_hasChanges()) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('Annuler les modifications'),
          content: const Text('Vous avez des modifications non sauvegardées. Êtes-vous sûr de vouloir les abandonner ?'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Continuer l\'édition'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop(); // Fermer le dialog
                Navigator.of(context).pop(); // Retour à la page précédente
              },
              style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
              child: const Text('Abandonner', style: TextStyle(color: Colors.white)),
            ),
          ],
        ),
      );
    } else {
      Navigator.of(context).pop();
    }
  }

  /// Formate une date
  String _formatDate(DateTime? date) {
    if (date == null) return 'Non spécifiée';
    return '${date.day}/${date.month}/${date.year}';
  }
}
