import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../../shared/design_system/unionflow_design_v2.dart';
import '../../../../../shared/design_system/tokens/module_colors.dart';
import '../../../../../shared/design_system/tokens/color_tokens.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';
import '../../../../notifications/presentation/pages/notifications_page_wrapper.dart';

/// Dashboard Super Admin — design harmonisé v2
///
/// Corrections v2 :
///  • Dark mode : _MemberActivityCard / _OrgTypeCard en StatelessWidget avec BuildContext
///  • Couleur module : ModuleColors.systeme (navy autorité) au lieu de UnionFlowColors.error
///  • ROOT badge : ModuleColors.solidariteGradient (rouge sémantique = root/danger)
///  • KPIs : ModuleColors.organisations/membres/evenements/cotisations
///  • Indicateur WebSocket dans l'AppBar
///  • États vides pour activités et événements
///  • Refresh via Completer (plus de Future.delayed artificiel)
///  • "Sécurité" → "Analytics" (supprime la duplication avec "Système")
class SuperAdminDashboard extends StatefulWidget {
  const SuperAdminDashboard({super.key});

  @override
  State<SuperAdminDashboard> createState() => _SuperAdminDashboardState();
}

class _SuperAdminDashboardState extends State<SuperAdminDashboard> {
  Completer<void>? _refreshCompleter;

  @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: BlocListener<DashboardBloc, DashboardState>(
        listener: (context, state) {
          if (state is DashboardLoaded || state is DashboardError) {
            _refreshCompleter?.complete();
            _refreshCompleter = null;
          }
        },
        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 ||
                    dashboardState is DashboardInitial) {
                  return const Center(
                    child: CircularProgressIndicator(
                      color: ModuleColors.systeme,
                      strokeWidth: 2,
                    ),
                  );
                }

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

                return RefreshIndicator(
                  color: ModuleColors.systeme,
                  strokeWidth: 2,
                  onRefresh: () async {
                    _refreshCompleter = Completer<void>();
                    context.read<DashboardBloc>().add(LoadDashboardData(
                          organizationId: dashboardData?.organizationId ?? '',
                          userId: user?.id ?? '',
                          useGlobalDashboard: true,
                        ));
                    return _refreshCompleter!.future;
                  },
                  child: SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // ── Carte identité ROOT ──────────────────────────
                        UserIdentityCard(
                          initials: user?.initials ?? 'SA',
                          name: user?.fullName ?? 'Super Administrateur',
                          subtitle: 'Accès global système',
                          badgeLabel: 'ROOT',
                          gradient: LinearGradient(
                            colors: ModuleColors.solidariteGradient,
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                          ),
                          accentColor: ModuleColors.solidarite,
                          showTopBorder: false,
                        ),
                        const SizedBox(height: 12),

                        // ── Caisse globale ───────────────────────────────
                        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),

                        // ── KPIs 3×2 ────────────────────────────────────
                        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: ModuleColors.organisations,
                            ),
                            UnionStatWidget(
                              label: 'Utilisateurs',
                              value: '${stats?.totalMembers ?? 0}',
                              icon: Icons.groups_rounded,
                              color: ModuleColors.membres,
                              trend: stats != null && stats.monthlyGrowth > 0
                                  ? '+${stats.monthlyGrowth.toStringAsFixed(0)}%'
                                  : null,
                            ),
                            UnionStatWidget(
                              label: 'Événements',
                              value: '${stats?.totalEvents ?? 0}',
                              icon: Icons.event_rounded,
                              color: ModuleColors.evenements,
                              trend: stats != null && stats.upcomingEvents > 0
                                  ? '${stats.upcomingEvents} à venir'
                                  : null,
                            ),
                            UnionStatWidget(
                              label: 'Cotisations',
                              value: '${stats?.totalContributions ?? 0}',
                              icon: Icons.payments_rounded,
                              color: ModuleColors.cotisations,
                            ),
                            UnionStatWidget(
                              label: 'Demandes',
                              value: '${stats?.pendingRequests ?? 0}',
                              icon: Icons.pending_actions_rounded,
                              color: (stats?.pendingRequests ?? 0) > 0
                                  ? ColorTokens.warning
                                  : ColorTokens.success,
                            ),
                            UnionStatWidget(
                              label: 'Engagement',
                              value: stats != null
                                  ? '${(stats.engagementRate * 100).toStringAsFixed(0)}%'
                                  : '—',
                              icon: Icons.trending_up_rounded,
                              color: (stats?.engagementRate ?? 0) >= 0.7
                                  ? ColorTokens.success
                                  : ColorTokens.warning,
                            ),
                          ],
                        ),
                        const SizedBox(height: 12),

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

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

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

                        // ── Activités récentes ───────────────────────────
                        const UFSectionHeader('Activités récentes',
                            trailing: 'Dernières actions'),
                        const SizedBox(height: 6),
                        if (dashboardData != null && dashboardData.hasRecentActivity)
                          ...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),
                                ),
                              )
                        else
                          _EmptyStateRow(
                            icon: Icons.history_outlined,
                            message: 'Aucune activité récente',
                          ),
                        const SizedBox(height: 12),

                        // ── Actions rapides ──────────────────────────────
                        const UFSectionHeader('Actions rapides'),
                        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: ModuleColors.organisations,
                              onTap: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (_) =>
                                          const OrganizationsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Utilisateurs',
                              icon: Icons.people_rounded,
                              iconColor: ModuleColors.membres,
                              onTap: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (_) =>
                                          const UserManagementPage())),
                            ),
                            UnionActionButton(
                              label: 'Système',
                              icon: Icons.settings_rounded,
                              iconColor: ModuleColors.systeme,
                              onTap: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (_) =>
                                          const SystemSettingsPage())),
                            ),
                            UnionActionButton(
                              label: 'Backup',
                              icon: Icons.backup_rounded,
                              iconColor: ModuleColors.backup,
                              onTap: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (_) => const BackupPage())),
                            ),
                            // Bouton "Analytics" retiré : redondant avec
                            // l'item "Rapports & Analytics" du menu "Plus".
                            UnionActionButton(
                              label: 'Support',
                              icon: Icons.help_outline_rounded,
                              iconColor: ModuleColors.support,
                              onTap: () => Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (_) =>
                                          const HelpSupportPage())),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }

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

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    // L'AppBar a toujours un fond gradient sombre (navy) — les icônes de status bar
    // sont donc toujours claires, indépendamment du thème de l'app.
    return AppBar(
      backgroundColor: Colors.transparent,
      foregroundColor: Colors.white,
      elevation: 0,
      scrolledUnderElevation: 0, // Pas de surface tint sur le gradient
      systemOverlayStyle: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.light,  // icônes blanches sur gradient sombre
        statusBarBrightness: Brightness.dark,        // iOS : barre sombre
      ),
      flexibleSpace: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: ModuleColors.systemeGradient,
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        ),
      ),
      leading: Builder(
        builder: (ctx) => IconButton(
          icon: const Icon(Icons.menu, size: 22, color: Colors.white),
          onPressed: () => Scaffold.of(ctx).openDrawer(),
        ),
      ),
      title: Row(
        children: [
          // Badge ROOT
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: ModuleColors.solidariteGradient,
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              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),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: const [
              Text(
                'UnionFlow',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w700,
                  color: Colors.white,
                ),
              ),
              Text(
                'Super Admin',
                style: TextStyle(fontSize: 10, color: Colors.white70),
              ),
            ],
          ),
        ],
      ),
      actions: [
        IconButton(
          icon: const Icon(Icons.notifications_outlined, color: Colors.white),
          onPressed: () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const NotificationsPageWrapper())),
          tooltip: 'Notifications',
        ),
        // Indicateur temps réel WebSocket
        BlocBuilder<DashboardBloc, DashboardState>(
          builder: (context, state) {
            final isLive =
                state is DashboardLoaded || state is DashboardRefreshing;
            return Tooltip(
              message: isLive ? 'Temps réel actif' : 'En attente',
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 6),
                child: Container(
                  width: 8,
                  height: 8,
                  decoration: BoxDecoration(
                    color: isLive
                        ? ColorTokens.successLight
                        : Colors.white30,
                    shape: BoxShape.circle,
                    boxShadow: isLive
                        ? [
                            BoxShadow(
                              color: ColorTokens.successLight.withOpacity(0.6),
                              blurRadius: 6,
                            )
                          ]
                        : null,
                  ),
                ),
              ),
            );
          },
        ),
        UnionExportButton(onExport: (_) {}),
        const SizedBox(width: 6),
      ],
    );
  }

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

// ─── Widget : Activité membres (dark-mode aware) ───────────────────────────

class _MemberActivityCard extends StatelessWidget {
  final DashboardStatsEntity stats;
  const _MemberActivityCard({required this.stats});

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    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: scheme.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: scheme.outlineVariant),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                'Activité membres',
                style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w700,
                    color: scheme.onSurface),
              ),
              const Spacer(),
              Text(
                '$total membres',
                style: TextStyle(fontSize: 10, color: scheme.onSurfaceVariant),
              ),
            ],
          ),
          const SizedBox(height: 10),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: LinearProgressIndicator(
              value: pct,
              minHeight: 6,
              backgroundColor: scheme.outlineVariant,
              valueColor:
                  const AlwaysStoppedAnimation<Color>(ColorTokens.success),
            ),
          ),
          const SizedBox(height: 8),
          Row(
            children: [
              _dot(ColorTokens.success),
              const SizedBox(width: 4),
              Text('Actifs',
                  style: TextStyle(
                      fontSize: 10, color: scheme.onSurfaceVariant)),
              const SizedBox(width: 4),
              Text(
                '$active (${(pct * 100).toStringAsFixed(0)}%)',
                style: TextStyle(
                    fontSize: 10,
                    fontWeight: FontWeight.w700,
                    color: scheme.onSurface),
              ),
              const Spacer(),
              _dot(scheme.outlineVariant),
              const SizedBox(width: 4),
              Text('Inactifs',
                  style: TextStyle(
                      fontSize: 10, color: scheme.onSurfaceVariant)),
              const SizedBox(width: 4),
              Text(
                '$inactive (${total > 0 ? ((inactive / total) * 100).toStringAsFixed(0) : 0}%)',
                style: TextStyle(
                    fontSize: 10,
                    fontWeight: FontWeight.w700,
                    color: scheme.onSurface),
              ),
            ],
          ),
        ],
      ),
    );
  }

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

// ─── Widget : Répartition types d'org (dark-mode aware) ───────────────────

class _OrgTypeCard extends StatelessWidget {
  final DashboardStatsEntity stats;
  const _OrgTypeCard({required this.stats});

  static const _kColors = [
    ModuleColors.organisations,
    ModuleColors.membres,
    ModuleColors.evenements,
    ModuleColors.cotisations,
    ModuleColors.solidarite,
  ];

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    final dist = stats.organizationTypeDistribution!;
    final total = dist.values.fold(0, (s, v) => s + v);
    final entries = dist.entries.toList();

    return Container(
      padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
      decoration: BoxDecoration(
        color: scheme.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: scheme.outlineVariant),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                'Types d\'organisation',
                style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w700,
                    color: scheme.onSurface),
              ),
              const Spacer(),
              Text(
                '$total org.',
                style: TextStyle(fontSize: 10, color: scheme.onSurfaceVariant),
              ),
            ],
          ),
          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: _kColors[e.key % _kColors.length]),
                );
              }).toList(),
            ),
          ),
          const SizedBox(height: 8),
          ...entries.asMap().entries.map((e) {
            final color = _kColors[e.key % _kColors.length];
            final pct =
                total > 0 ? (e.value.value / total * 100).toStringAsFixed(0) : '0';
            return Padding(
              padding: const EdgeInsets.only(bottom: 4),
              child: Row(
                children: [
                  Container(
                    width: 8,
                    height: 8,
                    decoration: BoxDecoration(
                        color: color, shape: BoxShape.circle),
                  ),
                  const SizedBox(width: 6),
                  Expanded(
                    child: Text(
                      e.value.key,
                      style: TextStyle(
                          fontSize: 10, color: scheme.onSurfaceVariant),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Text(
                    '$pct% · ${e.value.value}',
                    style: TextStyle(
                        fontSize: 10,
                        fontWeight: FontWeight.w700,
                        color: scheme.onSurface),
                  ),
                ],
              ),
            );
          }),
        ],
      ),
    );
  }
}

// ─── Widget : État vide inline ─────────────────────────────────────────────

class _EmptyStateRow extends StatelessWidget {
  final IconData icon;
  final String message;
  const _EmptyStateRow({required this.icon, required this.message});

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        children: [
          Icon(icon, size: 16, color: scheme.onSurfaceVariant),
          const SizedBox(width: 8),
          Text(
            message,
            style: TextStyle(fontSize: 12, color: scheme.onSurfaceVariant),
          ),
        ],
      ),
    );
  }
}
