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

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

  @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.unionGreen),
                  );
                }

                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 Modérateur
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 100),
                        child: _buildUserHeader(user),
                      ),
                      const SizedBox(height: 24),

                      // Balance principale ou Vue Unifiée (Compte Adhérent)
                      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)}% ce mois'
                                    : 'Aucune variation',
                                isTrendPositive: (stats?.monthlyGrowth ?? 0) >= 0,
                              ),
                      ),
                      const SizedBox(height: 24),

                      // Bloc KPI unifié (4 stats regroupées)
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 250),
                        child: Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: UnionFlowColors.surface,
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(color: UnionFlowColors.border, width: 1),
                            boxShadow: UnionFlowColors.softShadow,
                          ),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    child: 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,
                                    ),
                                  ),
                                  const SizedBox(width: 12),
                                  Expanded(
                                    child: UnionStatWidget(
                                      label: 'Engagement',
                                      value: stats != null && stats.engagementRate > 0
                                          ? '${(stats.engagementRate * 100).toStringAsFixed(0)}%'
                                          : stats != null && stats.totalContributions > 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,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 12),
                              Row(
                                children: [
                                  Expanded(
                                    child: UnionStatWidget(
                                      label: 'Contribution Totale',
                                      value: _formatAmount(stats?.contributionsAmountOnly ?? stats?.totalContributionAmount ?? 0),
                                      icon: Icons.savings,
                                      color: UnionFlowColors.amber,
                                    ),
                                  ),
                                  const SizedBox(width: 12),
                                  Expanded(
                                    child: UnionStatWidget(
                                      label: 'Événements',
                                      value: '${stats?.upcomingEvents ?? 0}',
                                      icon: Icons.event_available,
                                      color: UnionFlowColors.terracotta,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Bloc Actions rapides unifié (6 boutons regroupés)
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 300),
                        child: Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: UnionFlowColors.surface,
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(color: UnionFlowColors.border, width: 1),
                            boxShadow: UnionFlowColors.softShadow,
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                'Actions Rapides',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w700,
                                  color: UnionFlowColors.textPrimary,
                                ),
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Expanded(
                                    child: UnionActionButton(
                                      label: 'Cotiser',
                                      icon: Icons.payment,
                                      onTap: () {
                                        Navigator.of(context).push(
                                          MaterialPageRoute<void>(
                                            builder: (_) => const CotisationsPageWrapper(),
                                          ),
                                        );
                                      },
                                      backgroundColor: UnionFlowColors.unionGreen,
                                    ),
                                  ),
                                  const SizedBox(width: 12),
                                  Expanded(
                                    child: UnionActionButton(
                                      label: 'Épargner',
                                      icon: Icons.savings_outlined,
                                      onTap: () {
                                        Navigator.of(context).push(
                                          MaterialPageRoute<void>(
                                            builder: (_) => const EpargnePage(),
                                          ),
                                        );
                                      },
                                      backgroundColor: UnionFlowColors.gold,
                                    ),
                                  ),
                                  const SizedBox(width: 12),
                                  Expanded(
                                    child: UnionActionButton(
                                      label: 'Crédit',
                                      icon: Icons.account_balance_wallet,
                                      onTap: () {
                                        Navigator.of(context).push(
                                          MaterialPageRoute<void>(
                                            builder: (_) => const EpargnePage(),
                                          ),
                                        );
                                      },
                                      backgroundColor: UnionFlowColors.amber,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 12),
                              Row(
                                children: [
                                  Expanded(
                                    child: UnionActionButton(
                                      label: 'Événements',
                                      icon: Icons.event,
                                      onTap: () {
                                        Navigator.of(context).push(
                                          MaterialPageRoute<void>(
                                            builder: (_) => const EventsPageWrapper(),
                                          ),
                                        );
                                      },
                                      backgroundColor: UnionFlowColors.terracotta,
                                    ),
                                  ),
                                  const SizedBox(width: 12),
                                  Expanded(
                                    child: UnionActionButton(
                                      label: 'Solidarité',
                                      icon: Icons.favorite_outline,
                                      onTap: () {
                                        Navigator.of(context).push(
                                          MaterialPageRoute<void>(
                                            builder: (_) => const DemandesAidePageWrapper(),
                                          ),
                                        );
                                      },
                                      backgroundColor: UnionFlowColors.error,
                                    ),
                                  ),
                                  const SizedBox(width: 12),
                                  Expanded(
                                    child: UnionActionButton(
                                      label: 'Profil',
                                      icon: Icons.person_outline,
                                      onTap: () {
                                        Navigator.of(context).push(
                                          MaterialPageRoute<void>(
                                            builder: (_) => const ProfilePageWrapper(),
                                          ),
                                        );
                                      },
                                      backgroundColor: UnionFlowColors.indigo,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 32),

                      // ——— Administration / Modération (tout en bas, après les actions membre) ———
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 600),
                        child: const Text(
                          'Espace Modérateur',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w700,
                            color: UnionFlowColors.textPrimary,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),

                      // Stats de modération (données backend réelles)
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 600),
                        child: Row(
                          children: [
                            Expanded(
                              child: 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,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: 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,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 300),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Événements',
                                value: '${stats?.upcomingEvents ?? 0}',
                                icon: Icons.event_outlined,
                                color: UnionFlowColors.gold,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Membres Total',
                                value: '${stats?.totalMembers ?? 0}',
                                icon: Icons.people_outline,
                                color: UnionFlowColors.unionGreen,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Activité des membres (données backend réelles)
                      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: 24),

                      // Demandes en attente (données backend)
                      if (dashboardData != null && dashboardData.hasRecentActivity) ...[
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 500),
                          child: const Text(
                            'Activité Récente à Modérer',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w700,
                              color: UnionFlowColors.textPrimary,
                            ),
                          ),
                        ),
                        const SizedBox(height: 16),
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 600),
                          child: Column(
                            children: dashboardData.recentActivities.take(4).map((activity) =>
                              Container(
                                margin: const EdgeInsets.only(bottom: 12),
                                padding: const EdgeInsets.all(14),
                                decoration: BoxDecoration(
                                  color: UnionFlowColors.surface,
                                  borderRadius: BorderRadius.circular(12),
                                  border: Border.all(color: UnionFlowColors.border, width: 1),
                                  boxShadow: UnionFlowColors.softShadow,
                                ),
                                child: Row(
                                  children: [
                                    CircleAvatar(
                                      radius: 22,
                                      backgroundColor: UnionFlowColors.indigo.withOpacity(0.2),
                                      child: Icon(
                                        activity.type == 'member' ? Icons.person_add :
                                        activity.type == 'event' ? Icons.event :
                                        Icons.info_outline,
                                        size: 20,
                                        color: UnionFlowColors.indigo,
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            activity.title,
                                            style: const TextStyle(
                                              fontSize: 13,
                                              fontWeight: FontWeight.w600,
                                              color: UnionFlowColors.textPrimary,
                                            ),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          const SizedBox(height: 4),
                                          Text(
                                            activity.description,
                                            style: const TextStyle(
                                              fontSize: 11,
                                              color: UnionFlowColors.textSecondary,
                                            ),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ],
                                      ),
                                    ),
                                    Text(
                                      activity.timeAgo,
                                      style: const TextStyle(
                                        fontSize: 11,
                                        color: UnionFlowColors.textTertiary,
                                      ),
                                    ),
                                  ],
                                ),
                              )
                            ).toList(),
                          ),
                        ),
                      ],
                      const SizedBox(height: 24),

                      // Actions de modération
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 700),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionActionButton(
                                label: 'Approuver',
                                icon: Icons.check_circle,
                                onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const AdhesionsPageWrapper())),
                                backgroundColor: UnionFlowColors.success,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Vérifier',
                                icon: Icons.visibility,
                                onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const AdhesionsPageWrapper())),
                                backgroundColor: UnionFlowColors.info,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Signaler',
                                icon: Icons.flag,
                                onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const HelpSupportPage())),
                                backgroundColor: UnionFlowColors.error,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 800),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionActionButton(
                                label: 'Membres',
                                icon: Icons.people,
                                onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const MembersPageWrapper())),
                                backgroundColor: UnionFlowColors.unionGreen,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Contenus',
                                icon: Icons.article,
                                onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const EventsPageWrapper())),
                                backgroundColor: UnionFlowColors.gold,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Historique',
                                icon: Icons.history,
                                onTap: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const ContributionsPageWrapper())),
                                backgroundColor: UnionFlowColors.indigo,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: UnionFlowColors.surface,
      elevation: 0,
      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),
          const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'UnionFlow',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w700,
                  color: UnionFlowColors.textPrimary,
                ),
              ),
              Text(
                'Modérateur',
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.w400,
                  color: UnionFlowColors.textSecondary,
                ),
              ),
            ],
          ),
        ],
      ),
      iconTheme: const IconThemeData(color: UnionFlowColors.textPrimary),
    );
  }

  Widget _buildUserHeader(dynamic user) {
    final year = user?.createdAt?.year ?? DateTime.now().year;
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: UnionFlowColors.warmGradient,
        borderRadius: BorderRadius.circular(16),
        border: const Border(
          top: BorderSide(color: UnionFlowColors.gold, width: 3),
        ),
        boxShadow: UnionFlowColors.goldGlowShadow,
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: 28,
            backgroundColor: Colors.white.withOpacity(0.3),
            child: Text(
              user?.initials ?? 'SM',
              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 ?? 'Secrétaire',
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w700,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Depuis $year • Très Actif',
                  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(
              'ACTIF',
              style: TextStyle(
                fontSize: 10,
                fontWeight: FontWeight.w800,
                color: UnionFlowColors.gold,
                letterSpacing: 0.5,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
