/// Page d'édition d'une organisation — tous les champs exhaustifs
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';
import '../../bloc/org_types_bloc.dart';
import '../../domain/entities/type_reference_entity.dart';
import '../../../../shared/design_system/tokens/app_colors.dart';
import '../../../../shared/design_system/tokens/module_colors.dart';
import '../../../../shared/design_system/components/uf_app_bar.dart';
import '../../../../core/di/injection_container.dart';

const List<String> _devisesEdit = ['XOF', 'XAF', 'EUR', 'USD', 'GBP', 'CAD', 'CHF', 'MAD', 'GHS', 'NGN', 'CDF', 'KES'];

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>();

  // Informations de base
  late final TextEditingController _nomController;
  late final TextEditingController _nomCourtController;
  late final TextEditingController _descriptionController;

  // Informations légales
  late final TextEditingController _numeroEnregistrementController;
  DateTime? _dateFondation;

  // Contact
  late final TextEditingController _emailController;
  late final TextEditingController _telephoneController;
  late final TextEditingController _telephoneSecondaireController;
  late final TextEditingController _emailSecondaireController;
  late final TextEditingController _siteWebController;
  late final TextEditingController _reseauxSociauxController;

  // Localisation
  late final TextEditingController _adresseController;
  late final TextEditingController _villeController;
  late final TextEditingController _codePostalController;
  late final TextEditingController _regionController;
  late final TextEditingController _paysController;

  // Finances
  late String _selectedDevise;
  late final TextEditingController _budgetAnnuelController;
  late bool _cotisationObligatoire;
  late final TextEditingController _montantCotisationAnnuelleController;

  // Mission & contenu
  late final TextEditingController _objectifsController;
  late final TextEditingController _activitesPrincipalesController;
  late final TextEditingController _certificationsController;
  late final TextEditingController _partenairesController;
  late final TextEditingController _notesController;

  // Configuration
  late String _selectedTypeCode;
  late StatutOrganization _selectedStatut;
  late bool _accepteNouveauxMembres;
  late bool _organisationPublique;

  late final OrgTypesBloc _orgTypesBloc;
  late final OrganizationsBloc _detailBloc;

  @override
  void initState() {
    super.initState();
    final org = widget.organization;

    _nomController = TextEditingController(text: org.nom);
    _nomCourtController = TextEditingController(text: org.nomCourt ?? '');
    _descriptionController = TextEditingController(text: org.description ?? '');
    _numeroEnregistrementController = TextEditingController(text: org.numeroEnregistrement ?? '');
    _dateFondation = org.dateFondation;

    _emailController = TextEditingController(text: org.email ?? '');
    _telephoneController = TextEditingController(text: org.telephone ?? '');
    _telephoneSecondaireController = TextEditingController(text: org.telephoneSecondaire ?? '');
    _emailSecondaireController = TextEditingController(text: org.emailSecondaire ?? '');
    _siteWebController = TextEditingController(text: org.siteWeb ?? '');
    _reseauxSociauxController = TextEditingController(text: org.reseauxSociaux ?? '');

    _adresseController = TextEditingController(text: org.adresse ?? '');
    _villeController = TextEditingController(text: org.ville ?? '');
    _codePostalController = TextEditingController(text: org.codePostal ?? '');
    _regionController = TextEditingController(text: org.region ?? '');
    _paysController = TextEditingController(text: org.pays ?? '');

    _selectedDevise = _devisesEdit.contains(org.devise) ? org.devise : 'XOF';
    _budgetAnnuelController = TextEditingController(text: org.budgetAnnuel?.toString() ?? '');
    _cotisationObligatoire = org.cotisationObligatoire;
    _montantCotisationAnnuelleController = TextEditingController(text: org.montantCotisationAnnuelle?.toString() ?? '');

    _objectifsController = TextEditingController(text: org.objectifs ?? '');
    _activitesPrincipalesController = TextEditingController(text: org.activitesPrincipales ?? '');
    _certificationsController = TextEditingController(text: org.certifications ?? '');
    _partenairesController = TextEditingController(text: org.partenaires ?? '');
    _notesController = TextEditingController(text: org.notes ?? '');

    _selectedTypeCode = org.typeOrganisation;
    _selectedStatut = org.statut;
    _accepteNouveauxMembres = org.accepteNouveauxMembres;
    _organisationPublique = org.organisationPublique;

    _orgTypesBloc = sl<OrgTypesBloc>()..add(const LoadOrgTypes());
    _detailBloc = sl<OrganizationsBloc>();
    if (org.id != null) {
      _detailBloc.add(LoadOrganizationById(org.id!));
    }
  }

  void _refillForm(OrganizationModel org) {
    _nomController.text = org.nom;
    _nomCourtController.text = org.nomCourt ?? '';
    _descriptionController.text = org.description ?? '';
    _numeroEnregistrementController.text = org.numeroEnregistrement ?? '';
    _emailController.text = org.email ?? '';
    _telephoneController.text = org.telephone ?? '';
    _telephoneSecondaireController.text = org.telephoneSecondaire ?? '';
    _emailSecondaireController.text = org.emailSecondaire ?? '';
    _siteWebController.text = org.siteWeb ?? '';
    _reseauxSociauxController.text = org.reseauxSociaux ?? '';
    _adresseController.text = org.adresse ?? '';
    _villeController.text = org.ville ?? '';
    _codePostalController.text = org.codePostal ?? '';
    _regionController.text = org.region ?? '';
    _paysController.text = org.pays ?? '';
    _budgetAnnuelController.text = org.budgetAnnuel?.toString() ?? '';
    _montantCotisationAnnuelleController.text = org.montantCotisationAnnuelle?.toString() ?? '';
    _objectifsController.text = org.objectifs ?? '';
    _activitesPrincipalesController.text = org.activitesPrincipales ?? '';
    _certificationsController.text = org.certifications ?? '';
    _partenairesController.text = org.partenaires ?? '';
    _notesController.text = org.notes ?? '';
    setState(() {
      _selectedTypeCode = org.typeOrganisation;
      _selectedStatut = org.statut;
      _dateFondation = org.dateFondation;
      _selectedDevise = _devisesEdit.contains(org.devise) ? org.devise : 'XOF';
      _cotisationObligatoire = org.cotisationObligatoire;
      _accepteNouveauxMembres = org.accepteNouveauxMembres;
      _organisationPublique = org.organisationPublique;
    });
  }

  @override
  void dispose() {
    _orgTypesBloc.close();
    _detailBloc.close();
    _nomController.dispose();
    _nomCourtController.dispose();
    _descriptionController.dispose();
    _numeroEnregistrementController.dispose();
    _emailController.dispose();
    _telephoneController.dispose();
    _telephoneSecondaireController.dispose();
    _emailSecondaireController.dispose();
    _siteWebController.dispose();
    _reseauxSociauxController.dispose();
    _adresseController.dispose();
    _villeController.dispose();
    _codePostalController.dispose();
    _regionController.dispose();
    _paysController.dispose();
    _budgetAnnuelController.dispose();
    _montantCotisationAnnuelleController.dispose();
    _objectifsController.dispose();
    _activitesPrincipalesController.dispose();
    _certificationsController.dispose();
    _partenairesController.dispose();
    _notesController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: UFAppBar(
        title: 'Modifier Organisation',
        moduleGradient: ModuleColors.organisationsGradient,
        actions: [
          TextButton(
            onPressed: _hasChanges() ? _saveChanges : null,
            child: const Text('Enregistrer', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600)),
          ),
        ],
      ),
      body: BlocListener<OrganizationsBloc, OrganizationsState>(
        bloc: _detailBloc,
        listener: (context, state) {
          if (state is OrganizationLoaded) _refillForm(state.organization);
        },
        child: 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: AppColors.success),
              );
              Navigator.of(context).pop(true);
            } else if (state is OrganizationsError) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text(state.message), backgroundColor: AppColors.error),
              );
            }
          },
          child: Form(
            key: _formKey,
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildSection('Informations de base', Icons.business, _buildBasicInfoFields()),
                  const SizedBox(height: 8),
                  _buildSection('Informations légales', Icons.gavel, _buildLegalFields()),
                  const SizedBox(height: 8),
                  _buildSection('Contact', Icons.contact_phone, _buildContactFields()),
                  const SizedBox(height: 8),
                  _buildSection('Localisation', Icons.location_on, _buildLocationFields()),
                  const SizedBox(height: 8),
                  _buildSection('Configuration', Icons.settings, _buildConfigurationFields()),
                  const SizedBox(height: 8),
                  _buildSection('Finances', Icons.account_balance_wallet, _buildFinancesFields()),
                  const SizedBox(height: 8),
                  _buildSection('Mission & Activités', Icons.flag, _buildMissionFields()),
                  const SizedBox(height: 8),
                  _buildSection('Informations complémentaires', Icons.info_outline, _buildSupplementaryFields()),
                  const SizedBox(height: 8),
                  _buildSection('Informations système', Icons.admin_panel_settings, _buildMetadataFields()),
                  const SizedBox(height: 8),
                  _buildActionButtons(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSection(String title, IconData icon, List<Widget> children) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(color: Theme.of(context).colorScheme.surface, borderRadius: BorderRadius.circular(8)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(children: [
            Icon(icon, size: 16, color: AppColors.primary),
            const SizedBox(width: 6),
            Text(title, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: AppColors.primary)),
          ]),
          const SizedBox(height: 10),
          ...children,
        ],
      ),
    );
  }

  List<Widget> _buildBasicInfoFields() => [
    TextFormField(
      controller: _nomController,
      decoration: const InputDecoration(labelText: 'Nom de l\'organisation *', border: OutlineInputBorder(), prefixIcon: Icon(Icons.business)),
      validator: (v) => v == null || v.trim().length < 3 ? 'Minimum 3 caractères' : null,
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _nomCourtController,
      decoration: const InputDecoration(labelText: 'Sigle / Nom court', border: OutlineInputBorder(), prefixIcon: Icon(Icons.short_text)),
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    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(),
          );
        }
        return DropdownButtonFormField<String>(
          value: types.any((t) => t.code == _selectedTypeCode) ? _selectedTypeCode : null,
          decoration: const InputDecoration(labelText: 'Type d\'organisation *', border: OutlineInputBorder(), prefixIcon: Icon(Icons.category)),
          items: types.map((t) => DropdownMenuItem(value: t.code, child: Text(t.libelle))).toList(),
          onChanged: (v) { if (v != null) setState(() => _selectedTypeCode = v); },
          validator: (v) => v == null ? 'Le type est obligatoire' : null,
        );
      },
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _descriptionController,
      decoration: const InputDecoration(labelText: 'Description', border: OutlineInputBorder(), prefixIcon: Icon(Icons.description)),
      maxLines: 3,
      validator: (v) => v != null && v.trim().isNotEmpty && v.trim().length < 10 ? 'Minimum 10 caractères' : null,
      onChanged: (_) => setState(() {}),
    ),
  ];

  List<Widget> _buildLegalFields() => [
    TextFormField(
      controller: _numeroEnregistrementController,
      decoration: const InputDecoration(labelText: 'Numéro d\'enregistrement officiel', border: OutlineInputBorder(), prefixIcon: Icon(Icons.assignment)),
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    InkWell(
      onTap: () => _pickDateFondation(context),
      child: InputDecorator(
        decoration: const InputDecoration(labelText: 'Date de fondation', border: OutlineInputBorder(), prefixIcon: Icon(Icons.cake)),
        child: Builder(
          builder: (ctx) {
            final isDark = Theme.of(ctx).brightness == Brightness.dark;
            return Text(
              _dateFondation != null ? _formatDate(_dateFondation) : 'Sélectionner une date',
              style: TextStyle(
                color: _dateFondation != null
                    ? (isDark ? AppColors.textPrimaryDark : AppColors.textPrimary)
                    : (isDark ? AppColors.textSecondaryDark : AppColors.textSecondary),
              ),
            );
          },
        ),
      ),
    ),
  ];

  List<Widget> _buildContactFields() => [
    TextFormField(
      controller: _emailController,
      decoration: const InputDecoration(labelText: 'Email principal *', border: OutlineInputBorder(), prefixIcon: Icon(Icons.email)),
      keyboardType: TextInputType.emailAddress,
      validator: (v) {
        if (v == null || v.trim().isEmpty) return 'L\'email est obligatoire';
        if (!RegExp(r'^[^@]+@[^@]+\.[^@]+$').hasMatch(v.trim())) return 'Format invalide';
        return null;
      },
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _emailSecondaireController,
      decoration: const InputDecoration(labelText: 'Email secondaire', border: OutlineInputBorder(), prefixIcon: Icon(Icons.alternate_email)),
      keyboardType: TextInputType.emailAddress,
      validator: (v) {
        if (v != null && v.trim().isNotEmpty && !RegExp(r'^[^@]+@[^@]+\.[^@]+$').hasMatch(v.trim())) return 'Format invalide';
        return null;
      },
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    Row(children: [
      Expanded(child: TextFormField(
        controller: _telephoneController,
        decoration: const InputDecoration(labelText: 'Téléphone principal', border: OutlineInputBorder(), prefixIcon: Icon(Icons.phone)),
        keyboardType: TextInputType.phone,
        onChanged: (_) => setState(() {}),
      )),
      const SizedBox(width: 8),
      Expanded(child: TextFormField(
        controller: _telephoneSecondaireController,
        decoration: const InputDecoration(labelText: 'Téléphone secondaire', border: OutlineInputBorder(), prefixIcon: Icon(Icons.phone_forwarded)),
        keyboardType: TextInputType.phone,
        onChanged: (_) => setState(() {}),
      )),
    ]),
    const SizedBox(height: 8),
    TextFormField(
      controller: _siteWebController,
      decoration: const InputDecoration(labelText: 'Site web', border: OutlineInputBorder(), prefixIcon: Icon(Icons.web)),
      keyboardType: TextInputType.url,
      validator: (v) {
        if (v != null && v.trim().isNotEmpty && !RegExp(r'^https?://[^\s]+$').hasMatch(v.trim())) return 'Doit commencer par http:// ou https://';
        return null;
      },
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _reseauxSociauxController,
      decoration: const InputDecoration(labelText: 'Réseaux sociaux', border: OutlineInputBorder(), prefixIcon: Icon(Icons.share)),
      maxLines: 2,
      onChanged: (_) => setState(() {}),
    ),
  ];

  List<Widget> _buildLocationFields() => [
    TextFormField(
      controller: _adresseController,
      decoration: const InputDecoration(labelText: 'Adresse', border: OutlineInputBorder(), prefixIcon: Icon(Icons.location_on)),
      maxLines: 2,
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    Row(children: [
      Expanded(child: TextFormField(
        controller: _villeController,
        decoration: const InputDecoration(labelText: 'Ville', border: OutlineInputBorder(), prefixIcon: Icon(Icons.location_city)),
        onChanged: (_) => setState(() {}),
      )),
      const SizedBox(width: 8),
      Expanded(child: TextFormField(
        controller: _codePostalController,
        decoration: const InputDecoration(labelText: 'Code postal', border: OutlineInputBorder(), prefixIcon: Icon(Icons.markunread_mailbox)),
        onChanged: (_) => setState(() {}),
      )),
    ]),
    const SizedBox(height: 8),
    Row(children: [
      Expanded(child: TextFormField(
        controller: _regionController,
        decoration: const InputDecoration(labelText: 'Région', border: OutlineInputBorder(), prefixIcon: Icon(Icons.map)),
        onChanged: (_) => setState(() {}),
      )),
      const SizedBox(width: 8),
      Expanded(child: TextFormField(
        controller: _paysController,
        decoration: const InputDecoration(labelText: 'Pays', border: OutlineInputBorder(), prefixIcon: Icon(Icons.flag)),
        onChanged: (_) => setState(() {}),
      )),
    ]),
  ];

  List<Widget> _buildConfigurationFields() => [
    DropdownButtonFormField<StatutOrganization>(
      value: _selectedStatut,
      decoration: const InputDecoration(labelText: 'Statut *', border: OutlineInputBorder(), prefixIcon: Icon(Icons.toggle_on)),
      items: StatutOrganization.values.map((s) {
        final color = Color(int.parse(s.color.substring(1), radix: 16) + 0xFF000000);
        return DropdownMenuItem(value: s, child: Row(children: [
          Container(width: 10, height: 10, decoration: BoxDecoration(color: color, shape: BoxShape.circle)),
          const SizedBox(width: 8),
          Text(s.displayName),
        ]));
      }).toList(),
      onChanged: (v) { if (v != null) setState(() => _selectedStatut = v); },
    ),
    const SizedBox(height: 8),
    SwitchListTile(
      dense: true,
      contentPadding: EdgeInsets.zero,
      title: const Text('Organisation publique', style: TextStyle(fontSize: 14)),
      subtitle: const Text('Visible par tous les utilisateurs', style: TextStyle(fontSize: 12)),
      value: _organisationPublique,
      onChanged: (v) => setState(() => _organisationPublique = v),
      activeColor: AppColors.primary,
    ),
    SwitchListTile(
      dense: true,
      contentPadding: EdgeInsets.zero,
      title: const Text('Accepte de nouveaux membres', style: TextStyle(fontSize: 14)),
      subtitle: const Text('Les demandes d\'adhésion sont ouvertes', style: TextStyle(fontSize: 12)),
      value: _accepteNouveauxMembres,
      onChanged: (v) => setState(() => _accepteNouveauxMembres = v),
      activeColor: AppColors.primary,
    ),
  ];

  List<Widget> _buildFinancesFields() => [
    DropdownButtonFormField<String>(
      value: _selectedDevise,
      decoration: const InputDecoration(labelText: 'Devise', border: OutlineInputBorder(), prefixIcon: Icon(Icons.currency_exchange)),
      items: _devisesEdit.map((d) => DropdownMenuItem(value: d, child: Text(d))).toList(),
      onChanged: (v) { if (v != null) setState(() => _selectedDevise = v); },
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _budgetAnnuelController,
      decoration: const InputDecoration(labelText: 'Budget annuel', border: OutlineInputBorder(), prefixIcon: Icon(Icons.account_balance)),
      keyboardType: const TextInputType.numberWithOptions(decimal: true),
      validator: (v) {
        if (v != null && v.trim().isNotEmpty && double.tryParse(v.trim()) == null) return 'Montant invalide';
        return null;
      },
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    SwitchListTile(
      dense: true,
      contentPadding: EdgeInsets.zero,
      title: const Text('Cotisation obligatoire', style: TextStyle(fontSize: 14)),
      value: _cotisationObligatoire,
      onChanged: (v) => setState(() => _cotisationObligatoire = v),
      activeColor: AppColors.primary,
    ),
    if (_cotisationObligatoire) ...[
      const SizedBox(height: 8),
      TextFormField(
        controller: _montantCotisationAnnuelleController,
        decoration: InputDecoration(labelText: 'Montant cotisation annuelle ($_selectedDevise)', border: const OutlineInputBorder(), prefixIcon: const Icon(Icons.payments)),
        keyboardType: const TextInputType.numberWithOptions(decimal: true),
        validator: (v) {
          if (_cotisationObligatoire && (v == null || v.trim().isEmpty)) return 'Obligatoire si cotisation requise';
          if (v != null && v.trim().isNotEmpty && double.tryParse(v.trim()) == null) return 'Montant invalide';
          return null;
        },
        onChanged: (_) => setState(() {}),
      ),
    ],
  ];

  List<Widget> _buildMissionFields() => [
    TextFormField(
      controller: _objectifsController,
      decoration: const InputDecoration(labelText: 'Objectifs', border: OutlineInputBorder(), prefixIcon: Icon(Icons.track_changes)),
      maxLines: 3,
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _activitesPrincipalesController,
      decoration: const InputDecoration(labelText: 'Activités principales', border: OutlineInputBorder(), prefixIcon: Icon(Icons.work)),
      maxLines: 3,
      onChanged: (_) => setState(() {}),
    ),
  ];

  List<Widget> _buildSupplementaryFields() => [
    TextFormField(
      controller: _certificationsController,
      decoration: const InputDecoration(labelText: 'Certifications / Agréments', border: OutlineInputBorder(), prefixIcon: Icon(Icons.verified)),
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _partenairesController,
      decoration: const InputDecoration(labelText: 'Partenaires', border: OutlineInputBorder(), prefixIcon: Icon(Icons.handshake)),
      maxLines: 2,
      onChanged: (_) => setState(() {}),
    ),
    const SizedBox(height: 8),
    TextFormField(
      controller: _notesController,
      decoration: const InputDecoration(labelText: 'Notes internes', border: OutlineInputBorder(), prefixIcon: Icon(Icons.sticky_note_2)),
      maxLines: 2,
      onChanged: (_) => setState(() {}),
    ),
  ];

  List<Widget> _buildMetadataFields() => [
    _buildReadOnlyRow(Icons.fingerprint, 'ID', widget.organization.id ?? '—'),
    const SizedBox(height: 8),
    _buildReadOnlyRow(Icons.calendar_today, 'Créé le', _formatDate(widget.organization.dateCreation)),
    const SizedBox(height: 8),
    _buildReadOnlyRow(Icons.edit_calendar, 'Modifié le', _formatDate(widget.organization.dateModification)),
    const SizedBox(height: 8),
    _buildReadOnlyRow(Icons.people, 'Membres', widget.organization.nombreMembres.toString()),
    const SizedBox(height: 8),
    _buildReadOnlyRow(Icons.admin_panel_settings, 'Administrateurs', widget.organization.nombreAdministrateurs.toString()),
  ];

  Widget _buildReadOnlyRow(IconData icon, String label, String value) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final textSecondary = isDark ? AppColors.textSecondaryDark : AppColors.textSecondary;
    final textPrimary = isDark ? AppColors.textPrimaryDark : AppColors.textPrimary;
    return Row(children: [
      Icon(icon, size: 18, color: textSecondary),
      const SizedBox(width: 10),
      Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(label, style: TextStyle(fontSize: 11, color: textSecondary)),
        Text(value, style: TextStyle(fontSize: 13, color: textPrimary, fontWeight: FontWeight.w600)),
      ])),
    ]);
  }

  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: AppColors.primary,
            foregroundColor: AppColors.onPrimary,
            padding: const EdgeInsets.symmetric(vertical: 10),
            textStyle: const TextStyle(fontSize: 14, 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: Theme.of(context).brightness == Brightness.dark ? AppColors.textSecondaryDark : AppColors.textSecondary, padding: const EdgeInsets.symmetric(vertical: 10)),
        ),
      ),
    ]);
  }

  bool _hasChanges() {
    final org = widget.organization;
    return _nomController.text.trim() != org.nom ||
        _nomCourtController.text.trim() != (org.nomCourt ?? '') ||
        _descriptionController.text.trim() != (org.description ?? '') ||
        _numeroEnregistrementController.text.trim() != (org.numeroEnregistrement ?? '') ||
        _dateFondation != org.dateFondation ||
        _emailController.text.trim() != (org.email ?? '') ||
        _telephoneController.text.trim() != (org.telephone ?? '') ||
        _telephoneSecondaireController.text.trim() != (org.telephoneSecondaire ?? '') ||
        _emailSecondaireController.text.trim() != (org.emailSecondaire ?? '') ||
        _siteWebController.text.trim() != (org.siteWeb ?? '') ||
        _reseauxSociauxController.text.trim() != (org.reseauxSociaux ?? '') ||
        _adresseController.text.trim() != (org.adresse ?? '') ||
        _villeController.text.trim() != (org.ville ?? '') ||
        _codePostalController.text.trim() != (org.codePostal ?? '') ||
        _regionController.text.trim() != (org.region ?? '') ||
        _paysController.text.trim() != (org.pays ?? '') ||
        _selectedDevise != org.devise ||
        _budgetAnnuelController.text.trim() != (org.budgetAnnuel?.toString() ?? '') ||
        _cotisationObligatoire != org.cotisationObligatoire ||
        _montantCotisationAnnuelleController.text.trim() != (org.montantCotisationAnnuelle?.toString() ?? '') ||
        _objectifsController.text.trim() != (org.objectifs ?? '') ||
        _activitesPrincipalesController.text.trim() != (org.activitesPrincipales ?? '') ||
        _certificationsController.text.trim() != (org.certifications ?? '') ||
        _partenairesController.text.trim() != (org.partenaires ?? '') ||
        _notesController.text.trim() != (org.notes ?? '') ||
        _selectedTypeCode != org.typeOrganisation ||
        _selectedStatut != org.statut ||
        _accepteNouveauxMembres != org.accepteNouveauxMembres ||
        _organisationPublique != org.organisationPublique;
  }

  void _saveChanges() {
    if (_formKey.currentState?.validate() ?? false) {
      final updated = 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: _selectedTypeCode,
        statut: _selectedStatut,
        dateFondation: _dateFondation,
        numeroEnregistrement: _numeroEnregistrementController.text.trim().isEmpty ? null : _numeroEnregistrementController.text.trim(),
        email: _emailController.text.trim().isEmpty ? null : _emailController.text.trim(),
        telephone: _telephoneController.text.trim().isEmpty ? null : _telephoneController.text.trim(),
        telephoneSecondaire: _telephoneSecondaireController.text.trim().isEmpty ? null : _telephoneSecondaireController.text.trim(),
        emailSecondaire: _emailSecondaireController.text.trim().isEmpty ? null : _emailSecondaireController.text.trim(),
        siteWeb: _siteWebController.text.trim().isEmpty ? null : _siteWebController.text.trim(),
        reseauxSociaux: _reseauxSociauxController.text.trim().isEmpty ? null : _reseauxSociauxController.text.trim(),
        adresse: _adresseController.text.trim().isEmpty ? null : _adresseController.text.trim(),
        ville: _villeController.text.trim().isEmpty ? null : _villeController.text.trim(),
        codePostal: _codePostalController.text.trim().isEmpty ? null : _codePostalController.text.trim(),
        region: _regionController.text.trim().isEmpty ? null : _regionController.text.trim(),
        pays: _paysController.text.trim().isEmpty ? null : _paysController.text.trim(),
        devise: _selectedDevise,
        budgetAnnuel: _budgetAnnuelController.text.trim().isEmpty ? null : double.tryParse(_budgetAnnuelController.text.trim()),
        cotisationObligatoire: _cotisationObligatoire,
        montantCotisationAnnuelle: _montantCotisationAnnuelleController.text.trim().isEmpty ? null : double.tryParse(_montantCotisationAnnuelleController.text.trim()),
        objectifs: _objectifsController.text.trim().isEmpty ? null : _objectifsController.text.trim(),
        activitesPrincipales: _activitesPrincipalesController.text.trim().isEmpty ? null : _activitesPrincipalesController.text.trim(),
        certifications: _certificationsController.text.trim().isEmpty ? null : _certificationsController.text.trim(),
        partenaires: _partenairesController.text.trim().isEmpty ? null : _partenairesController.text.trim(),
        notes: _notesController.text.trim().isEmpty ? null : _notesController.text.trim(),
        organisationPublique: _organisationPublique,
        accepteNouveauxMembres: _accepteNouveauxMembres,
      );
      if (widget.organization.id != null) {
        context.read<OrganizationsBloc>().add(UpdateOrganization(widget.organization.id!, updated));
      }
    }
  }

  void _showDiscardDialog() {
    if (!_hasChanges()) { Navigator.of(context).pop(); return; }
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Annuler les modifications'),
        content: const Text('Vous avez des modifications non sauvegardées. Voulez-vous les abandonner ?'),
        actions: [
          TextButton(onPressed: () => Navigator.of(ctx).pop(), child: const Text('Continuer l\'édition')),
          ElevatedButton(
            onPressed: () { Navigator.of(ctx).pop(); Navigator.of(context).pop(); },
            style: ElevatedButton.styleFrom(backgroundColor: AppColors.error),
            child: const Text('Abandonner', style: TextStyle(color: AppColors.onPrimary)),
          ),
        ],
      ),
    );
  }

  Future<void> _pickDateFondation(BuildContext context) async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _dateFondation ?? DateTime(2000),
      firstDate: DateTime(1800),
      lastDate: DateTime.now(),
    );
    if (picked != null) setState(() { _dateFondation = picked; });
  }

  String _formatDate(DateTime? date) {
    if (date == null) return '—';
    return '${date.day.toString().padLeft(2, '0')}/${date.month.toString().padLeft(2, '0')}/${date.year}';
  }
}
