/// 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 '../../../../../core/design_system/tokens/tokens.dart';
import '../../widgets/widgets.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
            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 Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Vue d\'ensemble Organisation',
          style: TypographyTokens.headlineMedium.copyWith(
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: SpacingTokens.md),
        
        DashboardStatsGrid(
          stats: [
            DashboardStat(
              icon: Icons.people,
              value: '156',
              title: 'Membres Actifs',
              color: const Color(0xFF00B894),
              onTap: () => _onStatTap('members'),
            ),
            DashboardStat(
              icon: Icons.euro,
              value: '12,450€',
              title: 'Budget Mensuel',
              color: const Color(0xFF0984E3),
              onTap: () => _onStatTap('budget'),
            ),
            DashboardStat(
              icon: Icons.event,
              value: '8',
              title: 'Événements',
              color: const Color(0xFFE17055),
              onTap: () => _onStatTap('events'),
            ),
            DashboardStat(
              icon: Icons.trending_up,
              value: '94%',
              title: 'Satisfaction',
              color: const Color(0xFF00CEC9),
              onTap: () => _onStatTap('satisfaction'),
            ),
          ],
          onStatTap: _onStatTap,
        ),
      ],
    );
  }

  /// 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),
          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),
        
        DashboardInsightsSection(
          metrics: [
            DashboardMetric(
              label: 'Cotisations collectées',
              value: '89%',
              progress: 0.89,
              color: const Color(0xFF00B894),
            ),
            DashboardMetric(
              label: 'Budget utilisé',
              value: '67%',
              progress: 0.67,
              color: const Color(0xFF0984E3),
            ),
            DashboardMetric(
              label: 'Objectif annuel',
              value: '78%',
              progress: 0.78,
              color: const Color(0xFFE17055),
            ),
          ],
        ),
      ],
    );
  }

  /// 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),
        
        DashboardRecentActivitySection(
          activities: [
            DashboardActivity(
              title: 'Nouveau membre approuvé',
              subtitle: 'Sophie Laurent rejoint l\'organisation',
              icon: Icons.person_add,
              color: const Color(0xFF00B894),
              time: 'Il y a 2h',
            ),
            DashboardActivity(
              title: 'Budget mis à jour',
              subtitle: 'Allocation événements modifiée',
              icon: Icons.account_balance_wallet,
              color: const Color(0xFF0984E3),
              time: 'Il y a 4h',
            ),
            DashboardActivity(
              title: 'Rapport généré',
              subtitle: 'Rapport mensuel d\'activité',
              icon: Icons.assessment,
              color: const Color(0xFF6C5CE7),
              time: 'Il y a 1j',
            ),
          ],
          onActivityTap: (activityId) => _onActivityTap(activityId),
        ),
      ],
    );
  }

  // === 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é
  }
}

/// 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;
}
