/// Dashboard Administrateur d'Organisation - Control Panel Sophistiqué
/// Gestion complète de l'organisation avec outils avancés
library org_admin_dashboard;

import 'package:flutter/material.dart';
import '../../../../../shared/design_system/unionflow_design_system.dart';


/// Dashboard Control Panel pour Administrateur d'Organisation
/// 
/// Fonctionnalités exclusives :
/// - Gestion complète des membres
/// - Contrôle financier avancé
/// - Configuration organisation
/// - Rapports et analytics
/// - Outils de communication
class OrgAdminDashboard extends StatefulWidget {
  const OrgAdminDashboard({super.key});

  @override
  State<OrgAdminDashboard> createState() => _OrgAdminDashboardState();
}

class _OrgAdminDashboardState extends State<OrgAdminDashboard> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorTokens.surface,
      body: CustomScrollView(
        slivers: [
          // App Bar avec gradient Org Admin
          SliverAppBar(
            expandedHeight: 180,
            floating: false,
            pinned: true,
            backgroundColor: const Color(0xFF0984E3), // Bleu corporate
            actions: [
              // Recherche des membres
              IconButton(
                icon: const Icon(Icons.search, color: Colors.white),
                onPressed: () {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('Recherche avancée - Fonctionnalité à implémenter'),
                      backgroundColor: Color(0xFF0984E3),
                    ),
                  );
                },
                tooltip: 'Rechercher des membres',
              ),
              // Notifications organisation
              IconButton(
                icon: const Icon(Icons.notifications_outlined, color: Colors.white),
                onPressed: () => _showOrgNotifications(),
                tooltip: 'Notifications organisation',
              ),
              // Menu d'options
              PopupMenuButton<String>(
                icon: const Icon(Icons.more_vert, color: Colors.white),
                onSelected: (value) {
                  switch (value) {
                    case 'settings':
                      _openOrgSettings();
                      break;
                    case 'reports':
                      _generateReports();
                      break;
                    case 'export':
                      _exportOrgData();
                      break;
                    case 'backup':
                      _backupOrgData();
                      break;
                  }
                },
                itemBuilder: (context) => [
                  const PopupMenuItem(
                    value: 'settings',
                    child: Row(
                      children: [
                        Icon(Icons.settings, size: 20, color: Color(0xFF0984E3)),
                        SizedBox(width: 12),
                        Text('Paramètres Org'),
                      ],
                    ),
                  ),
                  const PopupMenuItem(
                    value: 'reports',
                    child: Row(
                      children: [
                        Icon(Icons.assessment, size: 20, color: Color(0xFF0984E3)),
                        SizedBox(width: 12),
                        Text('Rapports'),
                      ],
                    ),
                  ),
                  const PopupMenuItem(
                    value: 'export',
                    child: Row(
                      children: [
                        Icon(Icons.download, size: 20, color: Color(0xFF0984E3)),
                        SizedBox(width: 12),
                        Text('Exporter données'),
                      ],
                    ),
                  ),
                  const PopupMenuItem(
                    value: 'backup',
                    child: Row(
                      children: [
                        Icon(Icons.backup, size: 20, color: Color(0xFF0984E3)),
                        SizedBox(width: 12),
                        Text('Sauvegarde'),
                      ],
                    ),
                  ),
                ],
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: const Text(
                'Control Panel',
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
              background: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Color(0xFF0984E3), // Bleu principal
                      Color(0xFF0770C4), // Bleu plus foncé
                      Color(0xFF055A9F), // Bleu profond
                    ],
                  ),
                ),
                child: Stack(
                  children: [
                    // Motif corporate
                    Positioned.fill(
                      child: CustomPaint(
                        painter: _CorporatePatternPainter(),
                      ),
                    ),
                    // Contenu de l'en-tête
                    Positioned(
                      bottom: 60,
                      left: 20,
                      right: 20,
                      child: Row(
                        children: [
                          Container(
                            width: 60,
                            height: 60,
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.2),
                              borderRadius: BorderRadius.circular(30),
                              border: Border.all(
                                color: Colors.white.withOpacity(0.3),
                                width: 2,
                              ),
                            ),
                            child: const Icon(
                              Icons.business_center,
                              color: Colors.white,
                              size: 30,
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  'Administrateur',
                                  style: TypographyTokens.headlineSmall.copyWith(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                Text(
                                  'Association des Développeurs',
                                  style: TypographyTokens.bodyMedium.copyWith(
                                    color: Colors.white.withOpacity(0.9),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          
          // Contenu principal
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(SpacingTokens.md),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Métriques organisation
                  _buildOrganizationMetricsSection(),
                  const SizedBox(height: SpacingTokens.xl),
                  
                  // Actions rapides admin
                  _buildAdminQuickActionsSection(),
                  const SizedBox(height: SpacingTokens.xl),
                  
                  // Gestion des membres
                  _buildMemberManagementSection(),
                  const SizedBox(height: SpacingTokens.xl),
                  
                  // Finances et budget
                  _buildFinancialOverviewSection(),
                  const SizedBox(height: SpacingTokens.xl),
                  
                  // Activité récente
                  _buildRecentActivitySection(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Section métriques organisation
  Widget _buildOrganizationMetricsSection() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: const Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Métriques Organisation',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16),
          Text('Statistiques de l\'organisation à implémenter'),
        ],
      ),
    );
  }

  /// Section actions rapides admin
  Widget _buildAdminQuickActionsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Actions Administrateur',
          style: TypographyTokens.headlineMedium.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: SpacingTokens.md),
        
        GridView.count(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          crossAxisCount: 2,
          crossAxisSpacing: SpacingTokens.md,
          mainAxisSpacing: SpacingTokens.md,
          childAspectRatio: 2.5,
          children: [
            _buildAdminActionCard(
              'Approuver Membres',
              '5 en attente',
              Icons.person_add,
              const Color(0xFF00B894),
              () => _onAdminAction('approve_members'),
            ),
            _buildAdminActionCard(
              'Gérer Budget',
              'Révision mensuelle',
              Icons.account_balance_wallet,
              const Color(0xFF0984E3),
              () => _onAdminAction('manage_budget'),
            ),
            _buildAdminActionCard(
              'Configurer Org',
              'Paramètres avancés',
              Icons.settings,
              const Color(0xFFE17055),
              () => _onAdminAction('configure_org'),
            ),
            _buildAdminActionCard(
              'Rapports',
              'Générer rapport',
              Icons.assessment,
              const Color(0xFF6C5CE7),
              () => _onAdminAction('generate_reports'),
            ),
          ],
        ),
      ],
    );
  }

  /// Carte d'action admin
  Widget _buildAdminActionCard(
    String title,
    String subtitle,
    IconData icon,
    Color color,
    VoidCallback onTap,
  ) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(RadiusTokens.md),
      child: Container(
        padding: const EdgeInsets.all(SpacingTokens.md),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(RadiusTokens.md),
          border: Border.all(
            color: color.withOpacity(0.2),
            width: 1,
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Icon(icon, color: color, size: 20),
            ),
            const SizedBox(width: SpacingTokens.sm),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    title,
                    style: TypographyTokens.bodyMedium.copyWith(
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    subtitle,
                    style: TypographyTokens.bodySmall.copyWith(
                      color: ColorTokens.textSecondary,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Section gestion des membres
  Widget _buildMemberManagementSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(
              'Gestion des Membres',
              style: TypographyTokens.headlineMedium.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const Spacer(),
            TextButton.icon(
              onPressed: () => _onViewAllMembers(),
              icon: const Icon(Icons.arrow_forward),
              label: const Text('Voir tout'),
            ),
          ],
        ),
        const SizedBox(height: SpacingTokens.md),
        
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(RadiusTokens.md),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 10,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            children: [
              _buildMemberItem(
                'Marie Dubois',
                'Demande d\'adhésion',
                Icons.person_add,
                Colors.orange,
                'En attente',
              ),
              const Divider(height: 1),
              _buildMemberItem(
                'Jean Martin',
                'Cotisation en retard',
                Icons.warning,
                Colors.red,
                '15 jours',
              ),
              const Divider(height: 1),
              _buildMemberItem(
                'Sophie Laurent',
                'Nouveau membre actif',
                Icons.check_circle,
                Colors.green,
                'Aujourd\'hui',
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// Item de membre
  Widget _buildMemberItem(
    String name,
    String status,
    IconData icon,
    Color color,
    String time,
  ) {
    return ListTile(
      leading: CircleAvatar(
        backgroundColor: color.withOpacity(0.1),
        child: Icon(icon, color: color, size: 20),
      ),
      title: Text(
        name,
        style: TypographyTokens.bodyMedium.copyWith(
          fontWeight: FontWeight.w600,
        ),
      ),
      subtitle: Text(status),
      trailing: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            time,
            style: TypographyTokens.bodySmall.copyWith(
              color: ColorTokens.textSecondary,
            ),
          ),
          const SizedBox(height: 2),
          const Icon(
            Icons.arrow_forward_ios,
            size: 12,
            color: ColorTokens.textSecondary,
          ),
        ],
      ),
      onTap: () => _onMemberTap(name),
    );
  }

  /// Section aperçu financier
  Widget _buildFinancialOverviewSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Aperçu Financier',
          style: TypographyTokens.headlineMedium.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: SpacingTokens.md),

        // Métriques serveur
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Performance Serveur',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              Text('Métriques serveur à implémenter'),
            ],
          ),
        ),
      ],
    );
  }

  /// Section activité récente
  Widget _buildRecentActivitySection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Activité Récente',
          style: TypographyTokens.headlineMedium.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: SpacingTokens.md),

        // Activités récentes de l'organisation
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'Activités Récentes',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              Text('Activités de l\'organisation à implémenter'),
            ],
          ),
        ),
      ],
    );
  }

  // === CALLBACKS ===

  void _onStatTap(String statType) {
    // Navigation vers les détails de la statistique
  }

  void _onAdminAction(String action) {
    // Exécuter l'action admin
  }

  void _onViewAllMembers() {
    // Navigation vers la liste complète des membres
  }

  void _onMemberTap(String memberName) {
    // Navigation vers le profil du membre
  }

  void _onActivityTap(String activityId) {
    // Navigation vers les détails de l'activité
  }

  /// Afficher les notifications de l'organisation
  void _showOrgNotifications() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.7,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
        ),
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.all(16),
              decoration: const BoxDecoration(
                color: Color(0xFF0984E3),
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
              ),
              child: Row(
                children: [
                  const Icon(Icons.business, color: Colors.white),
                  const SizedBox(width: 12),
                  const Text(
                    'Notifications Organisation',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const Spacer(),
                  IconButton(
                    onPressed: () => Navigator.pop(context),
                    icon: const Icon(Icons.close, color: Colors.white),
                  ),
                ],
              ),
            ),
            Expanded(
              child: ListView(
                padding: const EdgeInsets.all(16),
                children: [
                  _buildOrgNotificationItem(
                    'Nouveau membre',
                    'Marie Dubois a rejoint le département Marketing',
                    Icons.person_add,
                    const Color(0xFF00B894),
                    '10 min',
                  ),
                  _buildOrgNotificationItem(
                    'Budget dépassé',
                    'Le département IT a dépassé son budget mensuel',
                    Icons.warning,
                    const Color(0xFFE17055),
                    '1h',
                  ),
                  _buildOrgNotificationItem(
                    'Rapport mensuel',
                    'Le rapport d\'activité de mars est disponible',
                    Icons.assessment,
                    const Color(0xFF0984E3),
                    '2h',
                  ),
                  _buildOrgNotificationItem(
                    'Demande de congé',
                    '3 nouvelles demandes de congé en attente',
                    Icons.event_busy,
                    const Color(0xFFFDAB00),
                    '3h',
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Widget pour un élément de notification organisation
  Widget _buildOrgNotificationItem(
    String title,
    String message,
    IconData icon,
    Color color,
    String time,
  ) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: color.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(icon, color: color, size: 20),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: const TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 14,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  message,
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
          Text(
            time,
            style: TextStyle(
              color: Colors.grey[500],
              fontSize: 11,
            ),
          ),
        ],
      ),
    );
  }

  /// Ouvrir les paramètres de l'organisation
  void _openOrgSettings() {
    // TODO: Naviguer vers la page des paramètres organisation
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Paramètres Organisation - Fonctionnalité à implémenter'),
        backgroundColor: Color(0xFF0984E3),
      ),
    );
  }

  /// Générer des rapports
  void _generateReports() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Générer un rapport'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('Sélectionnez le type de rapport :'),
            const SizedBox(height: 16),
            ListTile(
              leading: const Icon(Icons.people, color: Color(0xFF0984E3)),
              title: const Text('Rapport Membres'),
              onTap: () {
                Navigator.pop(context);
                _generateMemberReport();
              },
            ),
            ListTile(
              leading: const Icon(Icons.attach_money, color: Color(0xFF00B894)),
              title: const Text('Rapport Financier'),
              onTap: () {
                Navigator.pop(context);
                _generateFinancialReport();
              },
            ),
            ListTile(
              leading: const Icon(Icons.analytics, color: Color(0xFFE17055)),
              title: const Text('Rapport d\'Activité'),
              onTap: () {
                Navigator.pop(context);
                _generateActivityReport();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Annuler'),
          ),
        ],
      ),
    );
  }

  /// Générer rapport des membres
  void _generateMemberReport() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Génération du rapport membres en cours...'),
        backgroundColor: Color(0xFF0984E3),
      ),
    );
  }

  /// Générer rapport financier
  void _generateFinancialReport() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Génération du rapport financier en cours...'),
        backgroundColor: Color(0xFF00B894),
      ),
    );
  }

  /// Générer rapport d'activité
  void _generateActivityReport() {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('Génération du rapport d\'activité en cours...'),
        backgroundColor: Color(0xFFE17055),
      ),
    );
  }

  /// Exporter les données de l'organisation
  void _exportOrgData() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Exporter les données'),
        content: const Text(
          'Sélectionnez le format d\'export souhaité :',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Annuler'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Export CSV en cours...'),
                  backgroundColor: Color(0xFF00B894),
                ),
              );
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF0984E3),
            ),
            child: const Text('CSV', style: TextStyle(color: Colors.white)),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Export Excel en cours...'),
                  backgroundColor: Color(0xFF00B894),
                ),
              );
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF0984E3),
            ),
            child: const Text('Excel', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  /// Sauvegarder les données de l'organisation
  void _backupOrgData() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Sauvegarde Organisation'),
        content: const Text(
          'Voulez-vous créer une sauvegarde complète des données de l\'organisation ?',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Annuler'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Sauvegarde en cours...'),
                  backgroundColor: Color(0xFF0984E3),
                ),
              );
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF0984E3),
            ),
            child: const Text('Confirmer', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }
}

/// Painter pour le motif corporate de l'en-tête
class _CorporatePatternPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.white.withOpacity(0.08)
      ..strokeWidth = 2
      ..style = PaintingStyle.stroke;

    // Dessiner un motif corporate sophistiqué
    for (int i = 0; i < 8; i++) {
      final path = Path();
      path.moveTo(i * size.width / 8, 0);
      path.lineTo(i * size.width / 8 + size.width / 16, size.height);
      canvas.drawPath(path, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
