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 '../../../../contributions/presentation/pages/contributions_page_wrapper.dart';
import '../../../../epargne/presentation/pages/epargne_page.dart';
import '../../../../profile/presentation/pages/profile_page_wrapper.dart';
import '../../../../events/presentation/pages/events_page_wrapper.dart';
import '../../../../solidarity/presentation/pages/demandes_aide_page_wrapper.dart';
import '../../../../adhesions/presentation/pages/adhesions_page_wrapper.dart';
import '../../../../members/presentation/pages/members_page_wrapper.dart';
import '../../../../help/presentation/pages/help_support_page.dart';
import '../../widgets/dashboard_drawer.dart';

/// Dashboard Modérateur - Design UnionFlow pour Gestion Communauté
class ModeratorDashboard extends StatelessWidget {
  const ModeratorDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: _buildAppBar(context),
      drawer: DashboardDrawer(
        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.unionGreen),
                  );
                }

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

                return RefreshIndicator(
                  color: UnionFlowColors.unionGreen,
                  onRefresh: () async {
                    final orgCtx = user?.organizationContexts.isNotEmpty == true
                        ? user!.organizationContexts.first : null;
                    context.read<DashboardBloc>().add(LoadDashboardData(
                      organizationId: orgCtx?.organizationId ?? '',
                      userId: user?.id ?? '',
                    ));
                    await Future.delayed(const Duration(milliseconds: 1200));
                  },
                  child: SingleChildScrollView(
                  physics: const AlwaysScrollableScrollPhysics(),
                  padding: const EdgeInsets.all(12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // En-tête Modérateur
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 100),
                        child: UserIdentityCard(
                          initials: user?.initials ?? 'SM',
                          name: user?.fullName ?? 'Secrétaire',
                          subtitle: 'Depuis ${user?.createdAt?.year ?? DateTime.now().year} · Très Actif',
                          badgeLabel: 'ACTIF',
                          gradient: UnionFlowColors.warmGradient,
                          accentColor: UnionFlowColors.gold,
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Balance / Vue Unifiée
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 200),
                        child: dashboardData?.monCompte != null
                            ? UnionUnifiedAccountCard(
                                numeroMembre: dashboardData!.monCompte!.numeroMembre,
                                organisationNom: dashboardData.monCompte!.organisationNom ?? 'UnionFlow',
                                soldeTotal: _formatAmount(dashboardData.monCompte!.soldeTotalDisponible),
                                capaciteEmprunt: _formatAmount(dashboardData.monCompte!.capaciteEmprunt),
                                epargneBloquee: _formatAmount(dashboardData.monCompte!.soldeBloque),
                                engagementRate: dashboardData.monCompte!.engagementRate,
                              )
                            : UnionBalanceCard(
                                label: 'Mon Solde Total',
                                amount: _formatAmount(stats?.totalContributionAmount ?? 0),
                                trend: stats != null && stats.monthlyGrowth != 0
                                    ? '${stats.monthlyGrowth > 0 ? '+' : ''}${stats.monthlyGrowth.toStringAsFixed(1)}%'
                                    : null,
                                isTrendPositive: (stats?.monthlyGrowth ?? 0) >= 0,
                              ),
                      ),
                      const SizedBox(height: 12),

                      // KPIs membre
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 250),
                        child: GridView.count(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          crossAxisCount: 2,
                          mainAxisSpacing: 6,
                          crossAxisSpacing: 6,
                          childAspectRatio: 2.0,
                          children: [
                            UnionStatWidget(
                              label: 'Cotisations',
                              value: '${stats?.totalContributions ?? 0}',
                              icon: Icons.check_circle,
                              color: (stats?.totalContributions ?? 0) > 0
                                  ? UnionFlowColors.success
                                  : UnionFlowColors.textTertiary,
                              trend: stats != null && stats.totalContributions > 0 && stats.engagementRate > 0
                                  ? (stats.engagementRate >= 1.0
                                      ? 'Tout payé'
                                      : '${(stats.engagementRate * 100).toStringAsFixed(0)}% payé')
                                  : null,
                              isTrendUp: (stats?.engagementRate ?? 0) >= 1.0,
                            ),
                            UnionStatWidget(
                              label: 'Engagement',
                              value: stats != null && stats.engagementRate > 0
                                  ? '${(stats.engagementRate * 100).toStringAsFixed(0)}%'
                                  : '0%',
                              icon: Icons.trending_up,
                              color: UnionFlowColors.gold,
                              trend: stats != null && stats.engagementRate > 0.9
                                  ? 'Excellent'
                                  : stats != null && stats.engagementRate > 0.5 ? 'Bon' : null,
                              isTrendUp: (stats?.engagementRate ?? 0) > 0.7,
                            ),
                            UnionStatWidget(
                              label: 'Contribution Totale',
                              value: _formatAmount(stats?.contributionsAmountOnly ?? stats?.totalContributionAmount ?? 0),
                              icon: Icons.savings,
                              color: UnionFlowColors.amber,
                            ),
                            UnionStatWidget(
                              label: 'Événements',
                              value: '${stats?.upcomingEvents ?? 0}',
                              icon: Icons.event_available,
                              color: UnionFlowColors.terracotta,
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Actions rapides membre
                      const AnimatedFadeIn(
                        delay: Duration(milliseconds: 300),
                        child: UFSectionHeader('Actions Rapides'),
                      ),
                      const SizedBox(height: 8),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 350),
                        child: GridView.count(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          crossAxisCount: 3,
                          mainAxisSpacing: 6,
                          crossAxisSpacing: 6,
                          childAspectRatio: 2.8,
                          children: [
                            UnionActionButton(
                              label: 'Cotiser',
                              icon: Icons.payment,
                              iconColor: UnionFlowColors.unionGreen,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const CotisationsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Épargner',
                              icon: Icons.savings_outlined,
                              iconColor: UnionFlowColors.gold,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const EpargnePage())),
                            ),
                            UnionActionButton(
                              label: 'Crédit',
                              icon: Icons.account_balance_wallet,
                              iconColor: UnionFlowColors.amber,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const EpargnePage())),
                            ),
                            UnionActionButton(
                              label: 'Événements',
                              icon: Icons.event,
                              iconColor: UnionFlowColors.terracotta,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const EventsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Solidarité',
                              icon: Icons.favorite_outline,
                              iconColor: UnionFlowColors.error,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const DemandesAidePageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Profil',
                              icon: Icons.person_outline,
                              iconColor: UnionFlowColors.indigo,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ProfilePageWrapper())),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 16),

                      // ——— Espace Modérateur ———
                      const AnimatedFadeIn(
                        delay: Duration(milliseconds: 600),
                        child: UFSectionHeader('Espace Modérateur'),
                      ),
                      const SizedBox(height: 8),

                      // Stats de modération
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 600),
                        child: GridView.count(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          crossAxisCount: 2,
                          mainAxisSpacing: 6,
                          crossAxisSpacing: 6,
                          childAspectRatio: 2.0,
                          children: [
                            UnionStatWidget(
                              label: 'En attente',
                              value: '${stats?.pendingRequests ?? 0}',
                              icon: Icons.pending_actions,
                              color: UnionFlowColors.warning,
                              trend: stats != null && stats.pendingRequests > 0 ? 'Action requise' : null,
                              isTrendUp: false,
                            ),
                            UnionStatWidget(
                              label: 'Membres Actifs',
                              value: '${stats?.activeMembers ?? 0}',
                              icon: Icons.check_circle_outline,
                              color: UnionFlowColors.success,
                              trend: stats != null && stats.totalMembers > 0
                                  ? '${((stats.activeMembers / stats.totalMembers) * 100).toStringAsFixed(0)}%'
                                  : null,
                              isTrendUp: true,
                            ),
                            UnionStatWidget(
                              label: 'Événements',
                              value: '${stats?.upcomingEvents ?? 0}',
                              icon: Icons.event_outlined,
                              color: UnionFlowColors.gold,
                            ),
                            UnionStatWidget(
                              label: 'Membres Total',
                              value: '${stats?.totalMembers ?? 0}',
                              icon: Icons.people_outline,
                              color: UnionFlowColors.unionGreen,
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Activité des membres
                      if (stats != null && stats.totalMembers > 0) ...[
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 400),
                          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.textTertiary,
                                title: '${(((stats.totalMembers - stats.activeMembers) / stats.totalMembers) * 100).toStringAsFixed(0)}%\nInactifs',
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 12),
                      ],

                      // Activité récente à modérer
                      if (dashboardData != null && dashboardData.hasRecentActivity) ...[
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 500),
                          child: const UFSectionHeader('Activité Récente à Modérer'),
                        ),
                        const SizedBox(height: 8),
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 600),
                          child: Column(
                            children: dashboardData.recentActivities.take(4).map((activity) =>
                              DashboardActivityRow(
                                title: activity.title,
                                description: activity.description,
                                timeAgo: activity.timeAgo,
                                icon: DashboardActivityRow.iconFor(activity.type),
                                color: DashboardActivityRow.colorFor(activity.type),
                              ),
                            ).toList(),
                          ),
                        ),
                        const SizedBox(height: 12),
                      ],

                      // Actions de modération
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 700),
                        child: GridView.count(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          crossAxisCount: 3,
                          mainAxisSpacing: 6,
                          crossAxisSpacing: 6,
                          childAspectRatio: 2.8,
                          children: [
                            UnionActionButton(
                              label: 'Approuver',
                              icon: Icons.check_circle,
                              iconColor: UnionFlowColors.success,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const AdhesionsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Vérifier',
                              icon: Icons.visibility,
                              iconColor: UnionFlowColors.info,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const AdhesionsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Signaler',
                              icon: Icons.flag,
                              iconColor: UnionFlowColors.error,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const HelpSupportPage())),
                            ),
                            UnionActionButton(
                              label: 'Membres',
                              icon: Icons.people,
                              iconColor: UnionFlowColors.unionGreen,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const MembersPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Contenus',
                              icon: Icons.article,
                              iconColor: UnionFlowColors.gold,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const EventsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Historique',
                              icon: Icons.history,
                              iconColor: UnionFlowColors.indigo,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ContributionsPageWrapper())),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),  // SingleChildScrollView
                );  // RefreshIndicator
              },
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: Theme.of(context).colorScheme.surface,
      elevation: 0,
      scrolledUnderElevation: 1,
      shadowColor: Theme.of(context).colorScheme.outline.withOpacity(0.2),
      title: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              gradient: UnionFlowColors.primaryGradient,
              borderRadius: BorderRadius.circular(8),
            ),
            alignment: Alignment.center,
            child: const Text('U', style: TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 18)),
          ),
          const SizedBox(width: 12),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('UnionFlow', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Theme.of(context).colorScheme.onSurface)),
              Text('Modérateur', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w400, color: Theme.of(context).colorScheme.onSurfaceVariant)),
            ],
          ),
        ],
      ),
      iconTheme: IconThemeData(color: Theme.of(context).colorScheme.onSurface),
    );
  }

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