import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/material.dart';
import '../../../../../shared/design_system/unionflow_design_v2.dart';
import '../../bloc/dashboard_bloc.dart';
import '../../../../authentication/presentation/bloc/auth_bloc.dart';
import '../../../../organizations/presentation/pages/organizations_page_wrapper.dart';
import '../../../../admin/presentation/pages/user_management_page.dart';
import '../../../../settings/presentation/pages/system_settings_page.dart';
import '../../../../backup/presentation/pages/backup_page.dart';
import '../../../../help/presentation/pages/help_support_page.dart';
import '../../widgets/dashboard_drawer.dart';

/// Dashboard Super Admin - Design UnionFlow Contrôle Système
class SuperAdminDashboard extends StatelessWidget {
  const SuperAdminDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UnionFlowColors.background,
      appBar: _buildAppBar(),
      drawer: DashboardDrawer(
        onNavigate: (route) {
          Navigator.of(context).pushNamed(route);
        },
        onLogout: () {
          context.read<AuthBloc>().add(const AuthLogoutRequested());
        },
      ),
      body: AfricanPatternBackground(
        child: BlocBuilder<AuthBloc, AuthState>(
          builder: (context, authState) {
            final user = (authState is AuthAuthenticated) ? authState.user : null;

            return BlocBuilder<DashboardBloc, DashboardState>(
              builder: (context, dashboardState) {
                if (dashboardState is DashboardLoading) {
                  return const Center(
                    child: CircularProgressIndicator(color: UnionFlowColors.error),
                  );
                }

                final dashboardData = (dashboardState is DashboardLoaded)
                    ? dashboardState.dashboardData
                    : null;
                final stats = dashboardData?.stats;

                return SingleChildScrollView(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // En-tête Root
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 100),
                        child: _buildUserHeader(user),
                      ),
                      const SizedBox(height: 24),

                      // Balance globale
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 200),
                        child: UnionBalanceCard(
                          label: 'Caisse Globale Système',
                          amount: _formatAmount(stats?.totalContributionAmount ?? 0),
                          trend: stats != null && stats.monthlyGrowth != 0
                              ? '${stats.monthlyGrowth > 0 ? '+' : ''}${stats.monthlyGrowth.toStringAsFixed(1)}% ce mois'
                              : 'Aucune variation',
                          isTrendPositive: (stats?.monthlyGrowth ?? 0) >= 0,
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Stats système
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 300),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Organisations',
                                value: stats != null ? '${stats.totalOrganizations ?? 0}' : '0',
                                icon: Icons.business_outlined,
                                color: UnionFlowColors.unionGreen,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Utilisateurs',
                                value: '${stats?.totalMembers ?? 0}',
                                icon: Icons.groups_outlined,
                                color: UnionFlowColors.gold,
                                trend: stats != null && stats.monthlyGrowth > 0
                                    ? '+${stats.monthlyGrowth.toStringAsFixed(0)}%'
                                    : null,
                                isTrendUp: (stats?.monthlyGrowth ?? 0) > 0,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 400),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Projets',
                                value: '${stats?.completedProjects ?? 0}',
                                icon: Icons.account_balance_outlined,
                                color: UnionFlowColors.info,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Engagement',
                                value: stats != null
                                    ? '${(stats.engagementRate * 100).toStringAsFixed(0)}%'
                                    : '0%',
                                icon: Icons.trending_up,
                                color: (stats?.engagementRate ?? 0) >= 0.7
                                    ? UnionFlowColors.success
                                    : UnionFlowColors.warning,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Répartition Membres (données réelles)
                      if (stats != null && stats.totalMembers > 0)
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 500),
                          child: UnionPieChart(
                            title: 'Activité des Membres',
                            subtitle: '${stats.totalMembers} membres au total',
                            sections: [
                              UnionPieChartSection.create(
                                value: stats.activeMembers.toDouble(),
                                color: UnionFlowColors.success,
                                title: '${((stats.activeMembers / stats.totalMembers) * 100).toStringAsFixed(0)}%\nActifs',
                              ),
                              UnionPieChartSection.create(
                                value: (stats.totalMembers - stats.activeMembers).toDouble(),
                                color: UnionFlowColors.warning,
                                title: '${(((stats.totalMembers - stats.activeMembers) / stats.totalMembers) * 100).toStringAsFixed(0)}%\nInactifs',
                              ),
                            ],
                          ),
                        ),
                      if (stats != null && stats.totalMembers > 0)
                        const SizedBox(height: 24),

                      // Événements à venir (données réelles)
                      if (dashboardData != null && dashboardData.hasUpcomingEvents)
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 600),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                'Événements à venir',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w700,
                                  color: UnionFlowColors.textPrimary,
                                ),
                              ),
                              const SizedBox(height: 12),
                              ...dashboardData.upcomingEvents.take(3).map((event) => Padding(
                                padding: const EdgeInsets.only(bottom: 8),
                                child: Container(
                                  padding: const EdgeInsets.all(12),
                                  decoration: BoxDecoration(
                                    color: UnionFlowColors.surface,
                                    borderRadius: BorderRadius.circular(12),
                                    border: Border(
                                      left: BorderSide(color: UnionFlowColors.unionGreen, width: 3),
                                    ),
                                  ),
                                  child: Row(
                                    children: [
                                      Icon(Icons.event, color: UnionFlowColors.unionGreen, size: 20),
                                      const SizedBox(width: 12),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              event.title,
                                              style: const TextStyle(
                                                fontSize: 13,
                                                fontWeight: FontWeight.w600,
                                                color: UnionFlowColors.textPrimary,
                                              ),
                                            ),
                                            const SizedBox(height: 2),
                                            Text(
                                              event.daysUntilEvent,
                                              style: const TextStyle(
                                                fontSize: 11,
                                                color: UnionFlowColors.textSecondary,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      Text(
                                        '${event.currentParticipants}/${event.maxParticipants}',
                                        style: const TextStyle(
                                          fontSize: 11,
                                          fontWeight: FontWeight.w600,
                                          color: UnionFlowColors.textSecondary,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              )),
                            ],
                          ),
                        ),
                      if (dashboardData != null && dashboardData.hasUpcomingEvents)
                        const SizedBox(height: 24),

                      // Activités récentes (données réelles)
                      if (dashboardData != null && dashboardData.hasRecentActivity)
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 650),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                'Activités Récentes',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w700,
                                  color: UnionFlowColors.textPrimary,
                                ),
                              ),
                              const SizedBox(height: 12),
                              ...dashboardData.recentActivities.take(5).map((activity) => Padding(
                                padding: const EdgeInsets.only(bottom: 8),
                                child: Container(
                                  padding: const EdgeInsets.all(12),
                                  decoration: BoxDecoration(
                                    color: UnionFlowColors.surface,
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: Row(
                                    children: [
                                      CircleAvatar(
                                        radius: 16,
                                        backgroundColor: UnionFlowColors.unionGreen.withOpacity(0.2),
                                        child: Text(
                                          activity.userName[0].toUpperCase(),
                                          style: const TextStyle(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w700,
                                            color: UnionFlowColors.unionGreen,
                                          ),
                                        ),
                                      ),
                                      const SizedBox(width: 12),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              activity.title,
                                              style: const TextStyle(
                                                fontSize: 12,
                                                fontWeight: FontWeight.w600,
                                                color: UnionFlowColors.textPrimary,
                                              ),
                                            ),
                                            Text(
                                              activity.description,
                                              style: const TextStyle(
                                                fontSize: 11,
                                                color: UnionFlowColors.textSecondary,
                                              ),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ],
                                        ),
                                      ),
                                      Text(
                                        activity.timeAgo,
                                        style: const TextStyle(
                                          fontSize: 10,
                                          color: UnionFlowColors.textTertiary,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              )),
                            ],
                          ),
                        ),
                      if (dashboardData != null && dashboardData.hasRecentActivity)
                        const SizedBox(height: 24),
                      const SizedBox(height: 24),

                      // Panel Root
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 700),
                        child: const Text(
                          'Panel Root',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w700,
                            color: UnionFlowColors.textPrimary,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 800),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionActionButton(
                                label: 'Organisations',
                                icon: Icons.business,
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => const OrganizationsPageWrapper(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.unionGreen,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Utilisateurs',
                                icon: Icons.people,
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => const UserManagementPage(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.gold,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Système',
                                icon: Icons.settings,
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => const SystemSettingsPage(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.indigo,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 900),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionActionButton(
                                label: 'Backup',
                                icon: Icons.backup,
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => const BackupPage(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.warning,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Sécurité',
                                icon: Icons.security,
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => const SystemSettingsPage(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.error,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Support',
                                icon: Icons.help_outline,
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => const HelpSupportPage(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.info,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: UnionFlowColors.surface,
      elevation: 0,
      title: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [UnionFlowColors.error, Colors.red.shade900],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              borderRadius: BorderRadius.circular(8),
            ),
            alignment: Alignment.center,
            child: const Text(
              'R',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w900,
                fontSize: 18,
              ),
            ),
          ),
          const SizedBox(width: 12),
          const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'UnionFlow',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w700,
                  color: UnionFlowColors.textPrimary,
                ),
              ),
              Text(
                'Super Admin (Root)',
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.w400,
                  color: UnionFlowColors.textSecondary,
                ),
              ),
            ],
          ),
        ],
      ),
      iconTheme: const IconThemeData(color: UnionFlowColors.textPrimary),
      actions: [
        UnionExportButton(
          onExport: (exportType) {},
        ),
        const SizedBox(width: 8),
      ],
    );
  }

  Widget _buildUserHeader(dynamic user) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [UnionFlowColors.error, Colors.red.shade900],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(16),
        border: const Border(
          top: BorderSide(color: UnionFlowColors.error, width: 3),
        ),
        boxShadow: [
          BoxShadow(
            color: UnionFlowColors.error.withOpacity(0.4),
            blurRadius: 16,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: 28,
            backgroundColor: Colors.white.withOpacity(0.3),
            child: Text(
              user?.initials ?? 'SA',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                color: Colors.white,
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  user?.fullName ?? 'Super Administrateur',
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w700,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Global System Root Access',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.white.withOpacity(0.9),
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Text(
              'ROOT',
              style: TextStyle(
                fontSize: 10,
                fontWeight: FontWeight.w800,
                color: UnionFlowColors.error,
                letterSpacing: 0.5,
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _formatAmount(double amount) {
    if (amount >= 1000000) {
      return '${(amount / 1000000).toStringAsFixed(1)}M FCFA';
    } else if (amount >= 1000) {
      return '${(amount / 1000).toStringAsFixed(0)}K FCFA';
    }
    return '${amount.toStringAsFixed(0)} FCFA';
  }
}
