/// Page de détail d'une organisation
/// Respecte strictement le design system établi dans l'application
library organisation_detail_page;

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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 'edit_organization_page.dart';

/// Page de détail d'une organisation avec design system cohérent
class OrganizationDetailPage extends StatefulWidget {
  final String organizationId;

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

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

class _OrganizationDetailPageState extends State<OrganizationDetailPage> {
  @override
  void initState() {
    super.initState();
    // Charger les détails de l'organisation
    context.read<OrganizationsBloc>().add(LoadOrganizationById(widget.organizationId));
  }

  @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('Détail Organisation'),
        elevation: 0,
        actions: [
          IconButton(
            onPressed: () => _showEditDialog(),
            icon: const Icon(Icons.edit),
            tooltip: 'Modifier',
          ),
          PopupMenuButton<String>(
            onSelected: (value) => _handleMenuAction(value),
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'activate',
                child: Row(
                  children: [
                    Icon(Icons.check_circle, color: Color(0xFF10B981)),
                    SizedBox(width: 8),
                    Text('Activer'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'deactivate',
                child: Row(
                  children: [
                    Icon(Icons.pause_circle, color: Color(0xFF6B7280)),
                    SizedBox(width: 8),
                    Text('Désactiver'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'delete',
                child: Row(
                  children: [
                    Icon(Icons.delete, color: Colors.red),
                    SizedBox(width: 8),
                    Text('Supprimer'),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      body: BlocBuilder<OrganizationsBloc, OrganizationsState>(
        builder: (context, state) {
          if (state is OrganizationLoading) {
            return _buildLoadingState();
          } else if (state is OrganizationLoaded) {
            return _buildDetailContent(state.organization);
          } else if (state is OrganizationsError) {
            return _buildErrorState(state);
          }
          return _buildEmptyState();
        },
      ),
    );
  }

  /// État de chargement
  Widget _buildLoadingState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF6C5CE7)),
          ),
          SizedBox(height: 16),
          Text(
            'Chargement des détails...',
            style: TextStyle(
              fontSize: 16,
              color: Color(0xFF6B7280),
            ),
          ),
        ],
      ),
    );
  }

  /// Contenu principal avec les détails
  Widget _buildDetailContent(OrganizationModel organization) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(12), // SpacingTokens cohérent
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeaderCard(organization),
          const SizedBox(height: 16),
          _buildInfoCard(organization),
          const SizedBox(height: 16),
          _buildStatsCard(organization),
          const SizedBox(height: 16),
          _buildContactCard(organization),
          const SizedBox(height: 16),
          _buildActionsCard(organization),
        ],
      ),
    );
  }

  /// Carte d'en-tête avec informations principales
  Widget _buildHeaderCard(OrganizationModel organization) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            const Color(0xFF6C5CE7),
            const Color(0xFF6C5CE7).withOpacity(0.8),
          ],
        ),
        borderRadius: BorderRadius.circular(8), // RadiusTokens cohérent
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  organization.typeOrganisation.icon,
                  style: const TextStyle(fontSize: 24),
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      organization.nom,
                      style: const TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                    if (organization.nomCourt?.isNotEmpty == true) ...[
                      const SizedBox(height: 4),
                      Text(
                        organization.nomCourt!,
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.white.withOpacity(0.9),
                        ),
                      ),
                    ],
                    const SizedBox(height: 8),
                    _buildStatusBadge(organization.statut),
                  ],
                ),
              ),
            ],
          ),
          if (organization.description?.isNotEmpty == true) ...[
            const SizedBox(height: 16),
            Text(
              organization.description!,
              style: TextStyle(
                fontSize: 14,
                color: Colors.white.withOpacity(0.9),
                height: 1.4,
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// Badge de statut
  Widget _buildStatusBadge(StatutOrganization statut) {


    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.2),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Text(
        statut.displayName,
        style: const TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w600,
          color: Colors.white,
        ),
      ),
    );
  }

  /// Carte d'informations générales
  Widget _buildInfoCard(OrganizationModel organization) {
    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 générales',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 16),
          _buildInfoRow(
            icon: Icons.category,
            label: 'Type',
            value: organization.typeOrganisation.displayName,
          ),
          const SizedBox(height: 12),
          _buildInfoRow(
            icon: Icons.location_on,
            label: 'Localisation',
            value: _buildLocationText(organization),
          ),
          const SizedBox(height: 12),
          _buildInfoRow(
            icon: Icons.calendar_today,
            label: 'Date de création',
            value: _formatDate(organization.dateCreation),
          ),
          if (organization.ancienneteAnnees > 0) ...[
            const SizedBox(height: 12),
            _buildInfoRow(
              icon: Icons.access_time,
              label: 'Ancienneté',
              value: '${organization.ancienneteAnnees} ans',
            ),
          ],
        ],
      ),
    );
  }

  /// Ligne d'information
  Widget _buildInfoRow({
    required IconData icon,
    required String label,
    required String value,
  }) {
    return Row(
      children: [
        Icon(
          icon,
          size: 20,
          color: const Color(0xFF6C5CE7),
        ),
        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,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// Carte de statistiques
  Widget _buildStatsCard(OrganizationModel organization) {
    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(
            'Statistiques',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  icon: Icons.people,
                  label: 'Membres',
                  value: organization.nombreMembres.toString(),
                  color: const Color(0xFF3B82F6),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildStatItem(
                  icon: Icons.event,
                  label: 'Événements',
                  value: (organization.nombreEvenements ?? 0).toString(),
                  color: const Color(0xFF10B981),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// Item de statistique
  Widget _buildStatItem({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.05),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(
          color: color.withOpacity(0.1),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Icon(
            icon,
            size: 24,
            color: color,
          ),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  /// Carte de contact
  Widget _buildContactCard(OrganizationModel organization) {
    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),
          if (organization.email?.isNotEmpty == true)
            _buildContactRow(
              icon: Icons.email,
              label: 'Email',
              value: organization.email!,
              onTap: () => _launchEmail(organization.email!),
            ),
          if (organization.telephone?.isNotEmpty == true) ...[
            const SizedBox(height: 12),
            _buildContactRow(
              icon: Icons.phone,
              label: 'Téléphone',
              value: organization.telephone!,
              onTap: () => _launchPhone(organization.telephone!),
            ),
          ],
          if (organization.siteWeb?.isNotEmpty == true) ...[
            const SizedBox(height: 12),
            _buildContactRow(
              icon: Icons.web,
              label: 'Site web',
              value: organization.siteWeb!,
              onTap: () => _launchWebsite(organization.siteWeb!),
            ),
          ],
        ],
      ),
    );
  }

  /// Ligne de contact
  Widget _buildContactRow({
    required IconData icon,
    required String label,
    required String value,
    VoidCallback? onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(6),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          children: [
            Icon(
              icon,
              size: 20,
              color: const Color(0xFF6C5CE7),
            ),
            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: TextStyle(
                      fontSize: 14,
                      color: onTap != null ? const Color(0xFF6C5CE7) : const Color(0xFF374151),
                      fontWeight: FontWeight.w600,
                      decoration: onTap != null ? TextDecoration.underline : null,
                    ),
                  ),
                ],
              ),
            ),
            if (onTap != null)
              const Icon(
                Icons.open_in_new,
                size: 16,
                color: Color(0xFF6C5CE7),
              ),
          ],
        ),
      ),
    );
  }

  /// Carte d'actions
  Widget _buildActionsCard(OrganizationModel organization) {
    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(
            'Actions',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Color(0xFF6C5CE7),
            ),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: () => _showEditDialog(organization),
                  icon: const Icon(Icons.edit),
                  label: const Text('Modifier'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF6C5CE7),
                    foregroundColor: Colors.white,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: OutlinedButton.icon(
                  onPressed: () => _showDeleteConfirmation(organization),
                  icon: const Icon(Icons.delete),
                  label: const Text('Supprimer'),
                  style: OutlinedButton.styleFrom(
                    foregroundColor: Colors.red,
                    side: const BorderSide(color: Colors.red),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// État d'erreur
  Widget _buildErrorState(OrganizationsError state) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red.shade400,
          ),
          const SizedBox(height: 16),
          Text(
            'Erreur',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Colors.red.shade700,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            state.message,
            textAlign: TextAlign.center,
            style: const TextStyle(
              fontSize: 14,
              color: Color(0xFF6B7280),
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: () {
              context.read<OrganizationsBloc>().add(LoadOrganizationById(widget.organizationId));
            },
            icon: const Icon(Icons.refresh),
            label: const Text('Réessayer'),
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF6C5CE7),
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  /// État vide
  Widget _buildEmptyState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.business_outlined,
            size: 64,
            color: Color(0xFF6B7280),
          ),
          SizedBox(height: 16),
          Text(
            'Organisation non trouvée',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: Color(0xFF374151),
            ),
          ),
        ],
      ),
    );
  }

  /// Construit le texte de localisation
  String _buildLocationText(OrganizationModel organization) {
    final parts = <String>[];
    if (organization.ville?.isNotEmpty == true) {
      parts.add(organization.ville!);
    }
    if (organization.region?.isNotEmpty == true) {
      parts.add(organization.region!);
    }
    if (organization.pays?.isNotEmpty == true) {
      parts.add(organization.pays!);
    }
    return parts.isEmpty ? 'Non spécifiée' : parts.join(', ');
  }

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

  /// Actions du menu
  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;
    }
  }

  /// Ouvre la page d'édition ou le dialog selon le contexte
  void _showEditDialog([OrganizationModel? organization]) {
    if (organization == null) {
      final state = context.read<OrganizationsBloc>().state;
      if (state is OrganizationLoaded) {
        organization = state.organization;
      }
    }
    if (organization == null || !context.mounted) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Chargement de l\'organisation en cours...')),
        );
      }
      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));
      }
    });
  }

  /// Affiche la confirmation de suppression
  void _showDeleteConfirmation(OrganizationModel? organization) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Confirmer la suppression'),
        content: Text(
          organization != null
              ? 'Êtes-vous sûr de vouloir supprimer "${organization.nom}" ?'
              : 'Êtes-vous sûr de vouloir supprimer cette organisation ?',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Annuler'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              context.read<OrganizationsBloc>().add(DeleteOrganization(widget.organizationId));
              Navigator.of(context).pop(); // Retour à la liste
            },
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('Supprimer', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  /// Lance l'application email
  Future<void> _launchEmail(String email) async {
    final uri = Uri(scheme: 'mailto', path: email);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Impossible d\'ouvrir l\'email: $email')),
        );
      }
    }
  }

  /// Lance l'application téléphone
  Future<void> _launchPhone(String phone) async {
    final uri = Uri(scheme: 'tel', path: phone);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Impossible d\'appeler: $phone')),
        );
      }
    }
  }

  /// Lance le navigateur web
  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);
    } else {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Impossible d\'ouvrir: $url')),
        );
      }
    }
  }
}
