/// Page de détail d'une organisation — affichage exhaustif de tous les champs
library organisation_detail_page;

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it/get_it.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../data/models/organization_model.dart';
import '../../bloc/organizations_bloc.dart';
import '../../bloc/organizations_event.dart';
import '../../bloc/organizations_state.dart';
import '../../domain/repositories/organization_repository.dart';
import 'edit_organization_page.dart';
import '../../../../shared/design_system/unionflow_design_system.dart';
import '../../../../features/authentication/presentation/bloc/auth_bloc.dart';
import '../../../../features/authentication/data/models/user_role.dart';


class OrganizationDetailPage extends StatefulWidget {
  final String organizationId;

  const OrganizationDetailPage({super.key, required this.organizationId});

  @override
  State<OrganizationDetailPage> createState() => _OrganizationDetailPageState();
}

class _OrganizationDetailPageState extends State<OrganizationDetailPage> {
  int? _memberCount;

  @override
  void initState() {
    super.initState();
    context.read<OrganizationsBloc>().add(LoadOrganizationById(widget.organizationId));
    _loadMemberCount();
  }

  Future<void> _loadMemberCount() async {
    try {
      final count = await GetIt.I<IOrganizationRepository>().getMembreCount(widget.organizationId);
      if (mounted) setState(() => _memberCount = count);
    } catch (_) {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: UFAppBar(
        title: 'Détail Organisation',
        moduleGradient: ModuleColors.organisationsGradient,
        actions: [
          Builder(builder: (ctx) {
            final authState = ctx.read<AuthBloc>().state;
            final canEdit = authState is AuthAuthenticated &&
                (authState.effectiveRole == UserRole.superAdmin ||
                    authState.effectiveRole == UserRole.orgAdmin);
            if (!canEdit) return const SizedBox.shrink();
            return IconButton(onPressed: _showEditPage, icon: const Icon(Icons.edit), tooltip: 'Modifier');
          }),
          Builder(builder: (ctx) {
            final authState = ctx.read<AuthBloc>().state;
            final isSuperAdmin = authState is AuthAuthenticated &&
                authState.effectiveRole == UserRole.superAdmin;
            if (!isSuperAdmin) return const SizedBox.shrink();
            return PopupMenuButton<String>(
              onSelected: _handleMenuAction,
              itemBuilder: (context) => [
                const PopupMenuItem(value: 'activate', child: Row(children: [Icon(Icons.check_circle, color: AppColors.success), SizedBox(width: SpacingTokens.md), Text('Activer')])),
                const PopupMenuItem(value: 'deactivate', child: Row(children: [Icon(Icons.pause_circle, color: AppColors.textSecondary), SizedBox(width: SpacingTokens.md), Text('Désactiver')])),
                const PopupMenuItem(value: 'delete', child: Row(children: [Icon(Icons.delete, color: AppColors.error), SizedBox(width: SpacingTokens.md), Text('Supprimer')])),
              ],
            );
          }),
        ],
      ),
      body: SafeArea(
        top: false,
        child: BlocBuilder<OrganizationsBloc, OrganizationsState>(
          builder: (context, state) {
            if (state is OrganizationLoading) return _buildLoading();
            if (state is OrganizationLoaded) return _buildContent(state.organization);
            if (state is OrganizationsError) return _buildError(state);
            return _buildEmpty();
          },
        ),
      ),
    );
  }

  Widget _buildContent(OrganizationModel org) {
    return RefreshIndicator(
      color: ModuleColors.organisations,
      onRefresh: () async => context
          .read<OrganizationsBloc>()
          .add(LoadOrganizationById(widget.organizationId)),
      child: SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      padding: const EdgeInsets.all(SpacingTokens.lg),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeaderCard(org),
          const SizedBox(height: SpacingTokens.md),
          _buildInfoCard(org),
          const SizedBox(height: SpacingTokens.md),
          _buildContactCard(org),
          if (_hasAddress(org)) ...[const SizedBox(height: SpacingTokens.md), _buildAddressCard(org)],
          const SizedBox(height: SpacingTokens.md),
          _buildStatsCard(org),
          if (_hasFinances(org)) ...[const SizedBox(height: SpacingTokens.md), _buildFinancesCard(org)],
          if (_hasMission(org)) ...[const SizedBox(height: SpacingTokens.md), _buildMissionCard(org)],
          if (_hasSupplementary(org)) ...[const SizedBox(height: SpacingTokens.md), _buildSupplementaryCard(org)],
          if (org.notes?.isNotEmpty == true) ...[const SizedBox(height: SpacingTokens.md), _buildNotesCard(org)],
          const SizedBox(height: SpacingTokens.md),
          _buildActionsCard(org),
        ],
      ),   // Column
      ),   // SingleChildScrollView
    );     // RefreshIndicator
  }

  // ── Header ─────────────────────────────────────────────────────────────────

  Widget _buildHeaderCard(OrganizationModel org) {
    return Container(
      padding: const EdgeInsets.all(SpacingTokens.lg),
      decoration: BoxDecoration(
        gradient: const LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ModuleColors.organisationsDark, ModuleColors.organisations]),
        borderRadius: BorderRadius.circular(SpacingTokens.radiusLg),
        boxShadow: [BoxShadow(color: AppColors.shadowMedium, blurRadius: 8, offset: const Offset(0, 2))],
      ),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [
          Container(
            padding: const EdgeInsets.all(SpacingTokens.lg),
            decoration: BoxDecoration(color: Colors.white.withOpacity(0.2), borderRadius: BorderRadius.circular(SpacingTokens.radiusMd)),
            child: const Icon(Icons.business_outlined, size: 24, color: Colors.white),
          ),
          const SizedBox(width: SpacingTokens.xl),
          Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(org.nom, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white)),
            if (org.nomCourt?.isNotEmpty == true) ...[
              const SizedBox(height: SpacingTokens.xs),
              Text(org.nomCourt!, style: TextStyle(fontSize: 13, color: Colors.white.withOpacity(0.9))),
            ],
            const SizedBox(height: SpacingTokens.md),
            Row(children: [
              _buildWhiteBadge(org.typeOrganisationLibelle ?? org.typeOrganisation),
              const SizedBox(width: SpacingTokens.md),
              _buildWhiteBadge(org.statutLibelle ?? org.statut.displayName),
            ]),
          ])),
        ]),
        if (org.description?.isNotEmpty == true) ...[
          const SizedBox(height: SpacingTokens.lg),
          Text(org.description!, style: TextStyle(fontSize: 13, color: Colors.white.withOpacity(0.9), height: 1.4)),
        ],
        const SizedBox(height: SpacingTokens.md),
        Row(children: [
          _buildBoolBadge(Icons.public, 'Public', org.organisationPublique),
          const SizedBox(width: SpacingTokens.md),
          _buildBoolBadge(Icons.person_add, 'Ouvert', org.accepteNouveauxMembres),
        ]),
      ]),
    );
  }

  Widget _buildWhiteBadge(String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: SpacingTokens.md, vertical: 3),
      decoration: BoxDecoration(color: Colors.white.withOpacity(0.2), borderRadius: BorderRadius.circular(SpacingTokens.radiusLg)),
      child: Text(text, style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: Colors.white)),
    );
  }

  Widget _buildBoolBadge(IconData icon, String label, bool value) {
    // Sur gradient : vert clair lisible pour TRUE, blanc translucide pour FALSE
    final color = value ? AppColors.successUI : Colors.white.withOpacity(0.6);
    return Row(mainAxisSize: MainAxisSize.min, children: [
      Icon(icon, size: 12, color: color),
      const SizedBox(width: SpacingTokens.sm),
      Text('$label: ${value ? 'Oui' : 'Non'}', style: TextStyle(fontSize: 11, color: color)),
    ]);
  }

  // ── Informations générales ──────────────────────────────────────────────────

  Widget _buildInfoCard(OrganizationModel org) {
    return _buildCard('Informations générales', Icons.info_outline, [
      if (org.dateFondation != null) _buildInfoRow(Icons.cake, 'Date de fondation', _formatDate(org.dateFondation)),
      if (org.dateFondation != null) const SizedBox(height: SpacingTokens.md),
      if (org.ancienneteAnnees > 0) _buildInfoRow(Icons.access_time, 'Ancienneté', '${org.ancienneteAnnees} an(s)'),
      if (org.ancienneteAnnees > 0) const SizedBox(height: SpacingTokens.md),
      if (org.numeroEnregistrement?.isNotEmpty == true) _buildInfoRow(Icons.assignment, 'N° d\'enregistrement', org.numeroEnregistrement!),
      if (org.numeroEnregistrement?.isNotEmpty == true) const SizedBox(height: SpacingTokens.md),
      _buildInfoRow(Icons.calendar_today, 'Créé dans le système', _formatDate(org.dateCreation)),
      if (org.dateModification != null) ...[
        const SizedBox(height: SpacingTokens.md),
        _buildInfoRow(Icons.edit_calendar, 'Dernière modification', _formatDate(org.dateModification)),
      ],
    ]);
  }

  // ── Contact ─────────────────────────────────────────────────────────────────

  Widget _buildContactCard(OrganizationModel org) {
    final hasAny = org.email?.isNotEmpty == true ||
        org.telephone?.isNotEmpty == true ||
        org.telephoneSecondaire?.isNotEmpty == true ||
        org.emailSecondaire?.isNotEmpty == true ||
        org.siteWeb?.isNotEmpty == true ||
        org.reseauxSociaux?.isNotEmpty == true;
    if (!hasAny) return const SizedBox.shrink();

    return _buildCard('Contact', Icons.contact_phone, [
      if (org.email?.isNotEmpty == true) _buildContactRow(Icons.email, 'Email', org.email!, onTap: () => _launchEmail(org.email!)),
      if (org.emailSecondaire?.isNotEmpty == true) ...[const SizedBox(height: SpacingTokens.md), _buildContactRow(Icons.alternate_email, 'Email secondaire', org.emailSecondaire!, onTap: () => _launchEmail(org.emailSecondaire!))],
      if (org.telephone?.isNotEmpty == true) ...[const SizedBox(height: SpacingTokens.md), _buildContactRow(Icons.phone, 'Téléphone', org.telephone!, onTap: () => _launchPhone(org.telephone!))],
      if (org.telephoneSecondaire?.isNotEmpty == true) ...[const SizedBox(height: SpacingTokens.md), _buildContactRow(Icons.phone_forwarded, 'Téléphone secondaire', org.telephoneSecondaire!, onTap: () => _launchPhone(org.telephoneSecondaire!))],
      if (org.siteWeb?.isNotEmpty == true) ...[const SizedBox(height: SpacingTokens.md), _buildContactRow(Icons.web, 'Site web', org.siteWeb!, onTap: () => _launchWebsite(org.siteWeb!))],
      if (org.reseauxSociaux?.isNotEmpty == true) ...[const SizedBox(height: SpacingTokens.md), _buildInfoRow(Icons.share, 'Réseaux sociaux', org.reseauxSociaux!)],
    ]);
  }

  // ── Adresse ─────────────────────────────────────────────────────────────────

  bool _hasAddress(OrganizationModel org) =>
      org.adresse?.isNotEmpty == true || org.ville?.isNotEmpty == true ||
      org.region?.isNotEmpty == true || org.pays?.isNotEmpty == true;

  Widget _buildAddressCard(OrganizationModel org) {
    return _buildCard('Localisation', Icons.location_on, [
      if (org.adresse?.isNotEmpty == true) _buildInfoRow(Icons.location_on, 'Adresse', org.adresse!),
      if (org.adresse?.isNotEmpty == true && (org.ville?.isNotEmpty == true)) const SizedBox(height: SpacingTokens.md),
      if (org.ville?.isNotEmpty == true) _buildInfoRow(Icons.location_city, 'Ville', '${org.ville!}${org.codePostal?.isNotEmpty == true ? ' — ${org.codePostal}' : ''}'),
      if (org.region?.isNotEmpty == true) ...[const SizedBox(height: SpacingTokens.md), _buildInfoRow(Icons.map, 'Région', org.region!)],
      if (org.pays?.isNotEmpty == true) ...[const SizedBox(height: SpacingTokens.md), _buildInfoRow(Icons.flag, 'Pays', org.pays!)],
    ]);
  }

  // ── Statistiques ─────────────────────────────────────────────────────────────

  Widget _buildStatsCard(OrganizationModel org) {
    return _buildCard('Statistiques', Icons.bar_chart, [
      Row(children: [
        Expanded(child: _buildStatItem(Icons.people, 'Membres', (_memberCount ?? org.nombreMembres).toString(), ModuleColors.organisations)),
        const SizedBox(width: SpacingTokens.md),
        Expanded(child: _buildStatItem(Icons.admin_panel_settings, 'Admins', org.nombreAdministrateurs.toString(), ModuleColors.organisationsDark)),
        const SizedBox(width: SpacingTokens.md),
        Expanded(child: _buildStatItem(Icons.event, 'Événements', (org.nombreEvenements ?? 0).toString(), AppColors.success)),
      ]),
    ]);
  }

  Widget _buildStatItem(IconData icon, String label, String value, Color color) {
    return Container(
      padding: const EdgeInsets.all(SpacingTokens.md),
      decoration: BoxDecoration(color: color.withOpacity(0.05), borderRadius: BorderRadius.circular(SpacingTokens.radiusMd), border: Border.all(color: color.withOpacity(0.15))),
      child: Column(children: [
        Icon(icon, size: 20, color: color),
        const SizedBox(height: SpacingTokens.sm),
        Text(value, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: color)),
        Text(label, style: TextStyle(fontSize: 11, color: color)),
      ]),
    );
  }

  // ── Finances ─────────────────────────────────────────────────────────────────

  bool _hasFinances(OrganizationModel org) =>
      org.budgetAnnuel != null || org.cotisationObligatoire || org.montantCotisationAnnuelle != null;

  Widget _buildFinancesCard(OrganizationModel org) {
    return _buildCard('Finances', Icons.account_balance_wallet, [
      _buildInfoRow(Icons.currency_exchange, 'Devise', org.devise),
      if (org.budgetAnnuel != null) ...[const SizedBox(height: SpacingTokens.md), _buildInfoRow(Icons.account_balance, 'Budget annuel', '${_formatMontant(org.budgetAnnuel)} ${org.devise}')],
      const SizedBox(height: SpacingTokens.md),
      _buildInfoRow(Icons.payments, 'Cotisation', org.cotisationObligatoire ? 'Obligatoire' : 'Facultative'),
      if (org.cotisationObligatoire && org.montantCotisationAnnuelle != null) ...[const SizedBox(height: SpacingTokens.md), _buildInfoRow(Icons.money, 'Montant annuel', '${_formatMontant(org.montantCotisationAnnuelle)} ${org.devise}')],
    ]);
  }

  // ── Mission ─────────────────────────────────────────────────────────────────

  bool _hasMission(OrganizationModel org) =>
      org.objectifs?.isNotEmpty == true || org.activitesPrincipales?.isNotEmpty == true;

  Widget _buildMissionCard(OrganizationModel org) {
    return _buildCard('Mission & Activités', Icons.flag, [
      if (org.objectifs?.isNotEmpty == true) _buildTextBlock(Icons.track_changes, 'Objectifs', org.objectifs!),
      if (org.objectifs?.isNotEmpty == true && org.activitesPrincipales?.isNotEmpty == true) const SizedBox(height: SpacingTokens.lg),
      if (org.activitesPrincipales?.isNotEmpty == true) _buildTextBlock(Icons.work, 'Activités principales', org.activitesPrincipales!),
    ]);
  }

  // ── Infos complémentaires ────────────────────────────────────────────────────

  bool _hasSupplementary(OrganizationModel org) =>
      org.certifications?.isNotEmpty == true || org.partenaires?.isNotEmpty == true;

  Widget _buildSupplementaryCard(OrganizationModel org) {
    return _buildCard('Informations complémentaires', Icons.info, [
      if (org.certifications?.isNotEmpty == true) _buildTextBlock(Icons.verified, 'Certifications / Agréments', org.certifications!),
      if (org.certifications?.isNotEmpty == true && org.partenaires?.isNotEmpty == true) const SizedBox(height: SpacingTokens.lg),
      if (org.partenaires?.isNotEmpty == true) _buildTextBlock(Icons.handshake, 'Partenaires', org.partenaires!),
    ]);
  }

  // ── Notes internes ──────────────────────────────────────────────────────────

  Widget _buildNotesCard(OrganizationModel org) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    return Container(
      padding: const EdgeInsets.all(SpacingTokens.lg),
      decoration: BoxDecoration(
        // Fond warning adaptatif (jaune clair light / surface sombre dark)
        color: isDark
            ? AppColors.surfaceVariantDark
            : AppColors.warningContainer,
        borderRadius: BorderRadius.circular(SpacingTokens.radiusMd),
        border: Border.all(color: AppColors.warningUI, width: 1),
      ),
      child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
        const Icon(Icons.sticky_note_2, size: 18, color: AppColors.warningUI),
        const SizedBox(width: SpacingTokens.md),
        Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text('Notes internes',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
                color: isDark ? AppColors.warningUI : AppColors.warning,
              )),
          const SizedBox(height: SpacingTokens.sm),
          Text(org.notes!,
              style: TextStyle(
                fontSize: 13,
                color: Theme.of(context).colorScheme.onSurface,
                height: 1.4,
              )),
        ])),
      ]),
    );
  }

  // ── Actions ─────────────────────────────────────────────────────────────────

  Widget _buildActionsCard(OrganizationModel org) {
    final authState = context.read<AuthBloc>().state;
    final isSuperAdmin = authState is AuthAuthenticated &&
        authState.effectiveRole == UserRole.superAdmin;
    final canEdit = authState is AuthAuthenticated &&
        (authState.effectiveRole == UserRole.superAdmin ||
            authState.effectiveRole == UserRole.orgAdmin);

    // Aucune action autorisée → ne pas afficher la section
    if (!canEdit) return const SizedBox.shrink();

    return _buildCard('Actions', Icons.bolt, [
      Row(children: [
        Expanded(child: ElevatedButton.icon(
          onPressed: _showEditPage,
          icon: const Icon(Icons.edit),
          label: const Text('Modifier'),
          style: ElevatedButton.styleFrom(backgroundColor: ModuleColors.organisations, foregroundColor: AppColors.onPrimary),
        )),
        if (isSuperAdmin) ...[
          const SizedBox(width: SpacingTokens.lg),
          Expanded(child: OutlinedButton.icon(
            onPressed: () => _showDeleteConfirmation(org),
            icon: const Icon(Icons.delete),
            label: const Text('Supprimer'),
            style: OutlinedButton.styleFrom(foregroundColor: AppColors.error, side: const BorderSide(color: AppColors.error)),
          )),
        ],
      ]),
    ]);
  }

  // ── Widgets helpers ─────────────────────────────────────────────────────────

  Widget _buildCard(String title, IconData icon, List<Widget> children) {
    return Container(
      padding: const EdgeInsets.all(SpacingTokens.lg),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        borderRadius: BorderRadius.circular(SpacingTokens.radiusLg),
        border: Border.all(color: Theme.of(context).colorScheme.outlineVariant, width: 1),
      ),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [
          Icon(icon, size: 15, color: ModuleColors.organisations),
          const SizedBox(width: SpacingTokens.md),
          Text(title, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold, color: ModuleColors.organisations)),
        ]),
        const SizedBox(height: SpacingTokens.md),
        ...children,
      ]),
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Icon(icon, size: 18, color: ModuleColors.organisations),
      const SizedBox(width: SpacingTokens.md),
      Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Text(label, style: TextStyle(fontSize: 11, color: Theme.of(context).colorScheme.onSurfaceVariant, fontWeight: FontWeight.w500)),
        const SizedBox(height: SpacingTokens.xs),
        Text(value, style: TextStyle(fontSize: 13, color: Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.w600)),
      ])),
    ]);
  }

  Widget _buildTextBlock(IconData icon, String label, String value) {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Row(children: [
        Icon(icon, size: 15, color: ModuleColors.organisations),
        const SizedBox(width: SpacingTokens.md),
        Text(label, style: TextStyle(fontSize: 12, color: Theme.of(context).colorScheme.onSurfaceVariant, fontWeight: FontWeight.w600)),
      ]),
      const SizedBox(height: SpacingTokens.sm),
      Text(value, style: TextStyle(fontSize: 13, color: Theme.of(context).colorScheme.onSurface, height: 1.5)),
    ]);
  }

  Widget _buildContactRow(IconData icon, String label, String value, {VoidCallback? onTap}) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(SpacingTokens.radiusMd),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 2),
        child: Row(children: [
          Icon(icon, size: 18, color: ModuleColors.organisations),
          const SizedBox(width: SpacingTokens.md),
          Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(label, style: TextStyle(fontSize: 11, color: Theme.of(context).colorScheme.onSurfaceVariant)),
            Text(value, style: TextStyle(fontSize: 13, color: onTap != null ? ModuleColors.organisations : Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.w600, decoration: onTap != null ? TextDecoration.underline : null)),
          ])),
          if (onTap != null) const Icon(Icons.open_in_new, size: 14, color: ModuleColors.organisations),
        ]),
      ),
    );
  }

  // ── États ────────────────────────────────────────────────────────────────────

  Widget _buildLoading() => const Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
    CircularProgressIndicator(color: ModuleColors.organisations),
    SizedBox(height: SpacingTokens.xl),
    Text('Chargement...'),
  ]));

  Widget _buildError(OrganizationsError state) => Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
    Icon(Icons.error_outline, size: 64, color: Theme.of(context).colorScheme.error),
    const SizedBox(height: SpacingTokens.xl),
    Text(state.message, textAlign: TextAlign.center, style: TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant)),
    const SizedBox(height: 24),
    FilledButton.icon(
      onPressed: () => context.read<OrganizationsBloc>().add(LoadOrganizationById(widget.organizationId)),
      icon: const Icon(Icons.refresh, size: 18),
      label: const Text('Réessayer'),
      style: FilledButton.styleFrom(backgroundColor: ModuleColors.organisations),
    ),
  ]));

  Widget _buildEmpty() => Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
    Icon(Icons.business_outlined, size: 64, color: Theme.of(context).colorScheme.onSurfaceVariant),
    const SizedBox(height: SpacingTokens.xl),
    Text('Organisation non trouvée', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Theme.of(context).colorScheme.onSurface)),
  ]));

  // ── Actions ──────────────────────────────────────────────────────────────────

  void _handleMenuAction(String action) {
    switch (action) {
      case 'activate': context.read<OrganizationsBloc>().add(ActivateOrganization(widget.organizationId)); break;
      case 'deactivate': context.read<OrganizationsBloc>().add(SuspendOrganization(widget.organizationId)); break;
      case 'delete': _showDeleteConfirmation(null); break;
    }
  }

  void _showEditPage([OrganizationModel? organization]) {
    if (organization == null) {
      final state = context.read<OrganizationsBloc>().state;
      if (state is OrganizationLoaded) organization = state.organization;
    }
    if (organization == null || !context.mounted) return;
    final org = organization;
    final bloc = context.read<OrganizationsBloc>();
    Navigator.of(context).push<void>(
      MaterialPageRoute<void>(builder: (_) => BlocProvider.value(value: bloc, child: EditOrganizationPage(organization: org))),
    ).then((_) { if (context.mounted) bloc.add(LoadOrganizationById(widget.organizationId)); });
  }

  void _showDeleteConfirmation(OrganizationModel? organization) {
    final bloc = context.read<OrganizationsBloc>();
    final nav = Navigator.of(context);
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Confirmer la suppression'),
        content: Text(organization != null ? 'Supprimer "${organization.nom}" ?' : 'Supprimer cette organisation ?'),
        actions: [
          TextButton(onPressed: () => Navigator.of(ctx).pop(), child: const Text('Annuler')),
          ElevatedButton(
            onPressed: () { Navigator.of(ctx).pop(); bloc.add(DeleteOrganization(widget.organizationId)); nav.pop(); },
            style: ElevatedButton.styleFrom(backgroundColor: AppColors.error),
            child: const Text('Supprimer', style: TextStyle(color: AppColors.onPrimary)),
          ),
        ],
      ),
    );
  }

  // ── Helpers ──────────────────────────────────────────────────────────────────

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

  String _formatMontant(double? v) {
    if (v == null) return '0';
    if (v >= 1000000) return '${(v / 1000000).toStringAsFixed(1)} M';
    if (v >= 1000) return '${(v / 1000).toStringAsFixed(0)} K';
    return v.toStringAsFixed(0);
  }

  Future<void> _launchEmail(String email) async {
    final uri = Uri(scheme: 'mailto', path: email);
    if (await canLaunchUrl(uri)) await launchUrl(uri);
  }

  Future<void> _launchPhone(String phone) async {
    final uri = Uri(scheme: 'tel', path: phone);
    if (await canLaunchUrl(uri)) await launchUrl(uri);
  }

  Future<void> _launchWebsite(String url) async {
    final uri = Uri.parse(url.startsWith('http') ? url : 'https://$url');
    if (await canLaunchUrl(uri)) await launchUrl(uri, mode: LaunchMode.externalApplication);
  }
}
