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 '../../../domain/entities/dashboard_entity.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 fintech compact
class SuperAdminDashboard extends StatelessWidget {
  const SuperAdminDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UnionFlowColors.background,
      appBar: _buildAppBar(context),
      drawer: DashboardDrawer(
        onNavigate: (route) => Navigator.of(context).pushNamed(route),
        onLogout: () => context.read<AuthBloc>().add(const AuthLogoutRequested()),
      ),
      body: 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,
                    strokeWidth: 2,
                  ),
                );
              }
              final dashboardData = (dashboardState is DashboardLoaded)
                  ? dashboardState.dashboardData
                  : null;
              final stats = dashboardData?.stats;

              return RefreshIndicator(
                color: UnionFlowColors.error,
                strokeWidth: 2,
                onRefresh: () async {
                  context.read<DashboardBloc>().add(LoadDashboardData(
                    organizationId: dashboardData?.organizationId ?? '',
                    userId: user?.id ?? '',
                    useGlobalDashboard: true,
                  ));
                  await Future.delayed(const Duration(milliseconds: 600));
                },
                child: SingleChildScrollView(
                  physics: const AlwaysScrollableScrollPhysics(),
                  padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // ── Carte identité ───────────────────────────────
                      UserIdentityCard(
                        initials: user?.initials ?? 'SA',
                        name: user?.fullName ?? 'Super Administrateur',
                        subtitle: 'Accès global système',
                        badgeLabel: 'ROOT',
                        gradient: const LinearGradient(
                          colors: [Color(0xFFB91C1C), Color(0xFF7F1D1D)],
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                        ),
                        accentColor: UnionFlowColors.error,
                        showTopBorder: false,
                      ),
                      const SizedBox(height: 12),

                      // ── Balance principale ───────────────────────────
                      UnionBalanceCard(
                        label: 'Caisse Globale Système',
                        amount: _formatAmount(stats?.totalContributionAmount ?? 0),
                        trend: stats != null && stats.totalContributionAmount > 0
                            ? '${stats.monthlyGrowth >= 0 ? '+' : ''}${stats.monthlyGrowth.toStringAsFixed(1)}%'
                            : null,
                        isTrendPositive: (stats?.monthlyGrowth ?? 0) >= 0,
                      ),
                      const SizedBox(height: 12),

                      // ── Grille 3×2 KPIs ─────────────────────────────
                      GridView.count(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        crossAxisCount: 3,
                        mainAxisSpacing: 6,
                        crossAxisSpacing: 6,
                        childAspectRatio: 2.0,
                        children: [
                          UnionStatWidget(
                            label: 'Organisations',
                            value: '${stats?.totalOrganizations ?? 0}',
                            icon: Icons.business_rounded,
                            color: UnionFlowColors.unionGreen,
                          ),
                          UnionStatWidget(
                            label: 'Utilisateurs',
                            value: '${stats?.totalMembers ?? 0}',
                            icon: Icons.groups_rounded,
                            color: UnionFlowColors.gold,
                            trend: stats != null && stats.monthlyGrowth > 0
                                ? '+${stats.monthlyGrowth.toStringAsFixed(0)}%'
                                : null,
                          ),
                          UnionStatWidget(
                            label: 'Événements',
                            value: '${stats?.totalEvents ?? 0}',
                            icon: Icons.event_rounded,
                            color: UnionFlowColors.info,
                            trend: stats != null && stats.upcomingEvents > 0
                                ? '${stats.upcomingEvents} à venir'
                                : null,
                          ),
                          UnionStatWidget(
                            label: 'Cotisations',
                            value: '${stats?.totalContributions ?? 0}',
                            icon: Icons.payments_rounded,
                            color: UnionFlowColors.amber,
                          ),
                          UnionStatWidget(
                            label: 'Demandes',
                            value: '${stats?.pendingRequests ?? 0}',
                            icon: Icons.pending_actions_rounded,
                            color: (stats?.pendingRequests ?? 0) > 0
                                ? UnionFlowColors.warning
                                : UnionFlowColors.success,
                          ),
                          UnionStatWidget(
                            label: 'Engagement',
                            value: stats != null
                                ? '${(stats.engagementRate * 100).toStringAsFixed(0)}%'
                                : '—',
                            icon: Icons.trending_up_rounded,
                            color: (stats?.engagementRate ?? 0) >= 0.7
                                ? UnionFlowColors.success
                                : UnionFlowColors.warning,
                          ),
                        ],
                      ),
                      const SizedBox(height: 12),

                      // ── Activité membres (pie compact) ───────────────
                      if (stats != null && stats.totalMembers > 0) ...[
                        _buildMemberActivityRow(stats),
                        const SizedBox(height: 12),
                      ],

                      // ── Répartition types d'org ──────────────────────
                      if (stats?.organizationTypeDistribution != null &&
                          stats!.organizationTypeDistribution!.isNotEmpty) ...[
                        _buildOrgTypeRow(stats),
                        const SizedBox(height: 12),
                      ],

                      // ── Événements à venir ───────────────────────────
                      if (dashboardData != null && dashboardData.hasUpcomingEvents) ...[
                        UFSectionHeader(
                          'Événements à venir',
                          trailing: '${dashboardData.upcomingEvents.length} programmés',
                        ),
                        const SizedBox(height: 6),
                        ...dashboardData.upcomingEvents.take(3).map(
                              (e) => DashboardEventRow(
                                title: e.title,
                                date: e.formattedDate,
                                daysUntil: e.daysUntilEvent,
                                participants:
                                    '${e.currentParticipants}/${e.maxParticipants}',
                              ),
                            ),
                        const SizedBox(height: 12),
                      ],

                      // ── Activités récentes ───────────────────────────
                      if (dashboardData != null && dashboardData.hasRecentActivity) ...[
                        const UFSectionHeader('Activités récentes',
                            trailing: 'Dernières actions'),
                        const SizedBox(height: 6),
                        ...dashboardData.recentActivities.take(5).map(
                              (a) => DashboardActivityRow(
                                title: a.title,
                                description: a.description,
                                timeAgo: a.timeAgo,
                                icon: DashboardActivityRow.iconFor(a.type),
                                color: DashboardActivityRow.colorFor(a.type),
                              ),
                            ),
                        const SizedBox(height: 12),
                      ],

                      // ── Actions rapides ──────────────────────────────
                      const UFSectionHeader('Actions'),
                      const SizedBox(height: 8),
                      GridView.count(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        crossAxisCount: 3,
                        mainAxisSpacing: 6,
                        crossAxisSpacing: 6,
                        childAspectRatio: 2.8,
                        children: [
                          UnionActionButton(
                            label: 'Organisations',
                            icon: Icons.business_rounded,
                            iconColor: UnionFlowColors.unionGreen,
                            onTap: () => Navigator.push(context,
                                MaterialPageRoute(builder: (_) => const OrganizationsPageWrapper())),
                          ),
                          UnionActionButton(
                            label: 'Utilisateurs',
                            icon: Icons.people_rounded,
                            iconColor: UnionFlowColors.gold,
                            onTap: () => Navigator.push(context,
                                MaterialPageRoute(builder: (_) => const UserManagementPage())),
                          ),
                          UnionActionButton(
                            label: 'Système',
                            icon: Icons.settings_rounded,
                            iconColor: UnionFlowColors.indigo,
                            onTap: () => Navigator.push(context,
                                MaterialPageRoute(builder: (_) => const SystemSettingsPage())),
                          ),
                          UnionActionButton(
                            label: 'Backup',
                            icon: Icons.backup_rounded,
                            iconColor: UnionFlowColors.warning,
                            onTap: () => Navigator.push(context,
                                MaterialPageRoute(builder: (_) => const BackupPage())),
                          ),
                          UnionActionButton(
                            label: 'Sécurité',
                            icon: Icons.security_rounded,
                            iconColor: UnionFlowColors.error,
                            onTap: () => Navigator.push(context,
                                MaterialPageRoute(builder: (_) => const SystemSettingsPage())),
                          ),
                          UnionActionButton(
                            label: 'Support',
                            icon: Icons.help_outline_rounded,
                            iconColor: UnionFlowColors.info,
                            onTap: () => Navigator.push(context,
                                MaterialPageRoute(builder: (_) => const HelpSupportPage())),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }

  // ─── AppBar ────────────────────────────────────────────────────────────────

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: UnionFlowColors.surface,
      elevation: 0,
      scrolledUnderElevation: 1,
      shadowColor: UnionFlowColors.border,
      leading: Builder(
        builder: (ctx) => IconButton(
          icon: const Icon(Icons.menu, size: 22, color: UnionFlowColors.textPrimary),
          onPressed: () => Scaffold.of(ctx).openDrawer(),
        ),
      ),
      title: Row(
        children: [
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: UnionFlowColors.error,
              borderRadius: BorderRadius.circular(6),
            ),
            alignment: Alignment.center,
            child: const Text(
              'R',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w900,
                fontSize: 15,
              ),
            ),
          ),
          const SizedBox(width: 8),
          const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'UnionFlow',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w700,
                  color: UnionFlowColors.textPrimary,
                ),
              ),
              Text(
                'Super Admin',
                style: TextStyle(
                  fontSize: 10,
                  color: UnionFlowColors.textSecondary,
                ),
              ),
            ],
          ),
        ],
      ),
      actions: [
        UnionExportButton(onExport: (_) {}),
        const SizedBox(width: 6),
      ],
    );
  }

  // ─── Activité membres ─────────────────────────────────────────────────────

  Widget _buildMemberActivityRow(DashboardStatsEntity stats) {
    final total = stats.totalMembers;
    final active = stats.activeMembers;
    final inactive = total - active;
    final pct = total > 0 ? active / total : 0.0;

    return Container(
      padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
      decoration: BoxDecoration(
        color: UnionFlowColors.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: UnionFlowColors.border),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Text(
                'Activité membres',
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w700,
                  color: UnionFlowColors.textPrimary,
                ),
              ),
              const Spacer(),
              Text(
                '$total membres',
                style: const TextStyle(fontSize: 10, color: UnionFlowColors.textTertiary),
              ),
            ],
          ),
          const SizedBox(height: 10),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: LinearProgressIndicator(
              value: pct,
              minHeight: 6,
              backgroundColor: UnionFlowColors.border,
              valueColor: const AlwaysStoppedAnimation<Color>(UnionFlowColors.success),
            ),
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              _dot(UnionFlowColors.success),
              const SizedBox(width: 4),
              const Text('Actifs', style: TextStyle(fontSize: 10, color: UnionFlowColors.textSecondary)),
              const SizedBox(width: 4),
              Text(
                '$active (${(pct * 100).toStringAsFixed(0)}%)',
                style: const TextStyle(fontSize: 10, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
              ),
              const Spacer(),
              _dot(UnionFlowColors.border),
              const SizedBox(width: 4),
              const Text('Inactifs', style: TextStyle(fontSize: 10, color: UnionFlowColors.textSecondary)),
              const SizedBox(width: 4),
              Text(
                '$inactive (${total > 0 ? ((inactive / total) * 100).toStringAsFixed(0) : 0}%)',
                style: const TextStyle(fontSize: 10, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // ─── Répartition types d'org ──────────────────────────────────────────────

  Widget _buildOrgTypeRow(DashboardStatsEntity stats) {
    final dist = stats.organizationTypeDistribution!;
    final total = dist.values.fold(0, (s, v) => s + v);
    const colors = [
      UnionFlowColors.unionGreen,
      UnionFlowColors.gold,
      UnionFlowColors.info,
      UnionFlowColors.warning,
      UnionFlowColors.error,
    ];
    final entries = dist.entries.toList();

    return Container(
      padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
      decoration: BoxDecoration(
        color: UnionFlowColors.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: UnionFlowColors.border),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Text(
                'Types d\'organisation',
                style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
              ),
              const Spacer(),
              Text('$total org.', style: const TextStyle(fontSize: 10, color: UnionFlowColors.textTertiary)),
            ],
          ),
          const SizedBox(height: 10),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Row(
              children: entries.asMap().entries.map((e) {
                final frac = total > 0 ? e.value.value / total : 0.0;
                return Flexible(
                  flex: (frac * 100).round(),
                  child: Container(height: 6, color: colors[e.key % colors.length]),
                );
              }).toList(),
            ),
          ),
          const SizedBox(height: 8),
          ...entries.asMap().entries.map((e) {
            final color = colors[e.key % colors.length];
            final pct = total > 0 ? (e.value.value / total * 100).toStringAsFixed(0) : '0';
            return Padding(
              padding: const EdgeInsets.only(bottom: 4),
              child: Row(
                children: [
                  _dot(color),
                  const SizedBox(width: 6),
                  Expanded(
                    child: Text(
                      e.value.key,
                      style: const TextStyle(fontSize: 10, color: UnionFlowColors.textSecondary),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Text(
                    '$pct% · ${e.value.value}',
                    style: const TextStyle(fontSize: 10, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }

  Widget _dot(Color color) => Container(
        width: 8,
        height: 8,
        decoration: BoxDecoration(color: color, shape: BoxShape.circle),
      );

  // ─── Helpers ──────────────────────────────────────────────────────────────

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