import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/material.dart';
import '../../../../../shared/design_system/unionflow_design_v2.dart';
import '../../../../../core/di/injection_container.dart';
import '../../bloc/dashboard_bloc.dart';
import '../../../../authentication/presentation/bloc/auth_bloc.dart';
import '../../../../members/presentation/pages/members_page_wrapper.dart';
import '../../../../events/presentation/pages/events_page_wrapper.dart';
import '../../../../contributions/presentation/pages/contributions_page_wrapper.dart';
import '../../../../reports/presentation/pages/reports_page_wrapper.dart';
import '../../../../notifications/presentation/pages/notifications_page_wrapper.dart';
import '../../../../adhesions/presentation/pages/adhesions_page_wrapper.dart';
import '../../widgets/dashboard_drawer.dart';
import '../../../data/datasources/dashboard_remote_datasource.dart';
import '../../../data/services/dashboard_export_service.dart';
import 'package:share_plus/share_plus.dart';

/// Dashboard Admin Organisation - Design UnionFlow Gestion Complète
class OrgAdminDashboard extends StatelessWidget {
  const OrgAdminDashboard({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;
            final orgContext = user?.organizationContexts.isNotEmpty == true
                ? user!.organizationContexts.first
                : null;

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

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

                return RefreshIndicator(
                  color: UnionFlowColors.gold,
                  onRefresh: () async {
                    context.read<DashboardBloc>().add(LoadDashboardData(
                      organizationId: orgContext?.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 Admin
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 100),
                        child: UserIdentityCard(
                          initials: user?.initials ?? 'AD',
                          name: user?.fullName ?? 'Administrateur',
                          subtitle: orgContext?.organizationName ?? 'Organisation',
                          badgeLabel: 'ADMIN',
                          gradient: UnionFlowColors.goldGradient,
                          accentColor: UnionFlowColors.gold,
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Balance organisation
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 200),
                        child: UnionBalanceCard(
                          label: 'Caisse de l\'Organisation',
                          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),

                      // Stats organisation — cellules très plates
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 300),
                        child: GridView.count(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          crossAxisCount: 2,
                          mainAxisSpacing: 6,
                          crossAxisSpacing: 6,
                          childAspectRatio: 3.0,
                          children: [
                            UnionStatWidget(
                              compact: true,
                              label: 'Membres',
                              value: '${stats?.totalMembers ?? 0}',
                              icon: Icons.people_outlined,
                              color: UnionFlowColors.unionGreen,
                              trend: stats != null && stats.monthlyGrowth > 0
                                  ? '+${stats.monthlyGrowth.toStringAsFixed(1)}%'
                                  : null,
                              isTrendUp: (stats?.monthlyGrowth ?? 0) > 0,
                            ),
                            UnionStatWidget(
                              compact: true,
                              label: '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(
                              compact: true,
                              label: 'Événements',
                              value: '${stats?.upcomingEvents ?? 0}',
                              icon: Icons.event_outlined,
                              color: UnionFlowColors.gold,
                              trend: stats?.totalEvents != null ? '${stats!.totalEvents} total' : null,
                              isTrendUp: true,
                            ),
                            UnionStatWidget(
                              compact: true,
                              label: 'Cotisations',
                              value: '${stats?.totalContributions ?? 0}',
                              icon: Icons.trending_up,
                              color: UnionFlowColors.amber,
                              trend: _formatAmount(stats?.totalContributionAmount ?? 0),
                              isTrendUp: true,
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Répartition actifs / inactifs
                      if (stats != null && stats.totalMembers > 0) ...[
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 400),
                          child: UnionPieChart(
                            title: 'Activité des Membres',
                            subtitle: '${stats.totalMembers} membres',
                            sections: [
                              UnionPieChartSection.create(
                                value: stats.activeMembers.toDouble(),
                                color: UnionFlowColors.unionGreen,
                                title: stats.totalMembers > 0
                                    ? '${((stats.activeMembers / stats.totalMembers) * 100).toStringAsFixed(0)}%\nActifs'
                                    : '0%\nActifs',
                              ),
                              UnionPieChartSection.create(
                                value: (stats.totalMembers - stats.activeMembers).toDouble(),
                                color: UnionFlowColors.textTertiary,
                                title: stats.totalMembers > 0
                                    ? '${(((stats.totalMembers - stats.activeMembers) / stats.totalMembers) * 100).toStringAsFixed(0)}%\nInactifs'
                                    : '0%\nInactifs',
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 12),
                      ],

                      // Événements à venir
                      if (dashboardData != null && dashboardData.hasUpcomingEvents) ...[
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 500),
                          child: UFSectionHeader(
                            'Événements à Venir',
                            trailing: '${dashboardData.upcomingEvents.length} programmés',
                          ),
                        ),
                        const SizedBox(height: 8),
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 600),
                          child: Column(
                            children: dashboardData.upcomingEvents.take(3).map((event) =>
                              DashboardEventRow(
                                title: event.title,
                                date: event.formattedDate,
                                participants: event.hasParticipantInfo
                                    ? '${event.currentParticipants}/${event.maxParticipants}'
                                    : null,
                              ),
                            ).toList(),
                          ),
                        ),
                        const SizedBox(height: 12),
                      ],

                      // Activité récente
                      if (dashboardData != null && dashboardData.hasRecentActivity) ...[
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 520),
                          child: const UFSectionHeader('Activité Récente'),
                        ),
                        const SizedBox(height: 8),
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 580),
                          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),
                      ],

                      // Gestion de l'Organisation
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 800),
                        child: const UFSectionHeader('Gestion de l\'Organisation'),
                      ),
                      const SizedBox(height: 8),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 900),
                        child: GridView.count(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          crossAxisCount: 3,
                          mainAxisSpacing: 6,
                          crossAxisSpacing: 6,
                          childAspectRatio: 2.8,
                          children: [
                            UnionActionButton(
                              label: 'Membres',
                              icon: Icons.people,
                              iconColor: UnionFlowColors.unionGreen,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const MembersPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Finance',
                              icon: Icons.account_balance,
                              iconColor: UnionFlowColors.gold,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const CotisationsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Événements',
                              icon: Icons.event,
                              iconColor: UnionFlowColors.terracotta,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const EventsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Rapports',
                              icon: Icons.description,
                              iconColor: UnionFlowColors.info,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ReportsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Adhésions',
                              icon: Icons.person_add,
                              iconColor: UnionFlowColors.indigo,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const AdhesionsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Historique',
                              icon: Icons.history,
                              iconColor: UnionFlowColors.amber,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ReportsPageWrapper())),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),  // SingleChildScrollView
                );  // RefreshIndicator
              },
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    // Pattern aligné sur SuperAdminDashboard : AppBar + flexibleSpace gradient,
    // texte/icônes en blanc sur le gradient. Conserve l'identité "Admin Org"
    // via le badge « A » et le gradient gold spécifique au rôle.
    return AppBar(
      backgroundColor: Colors.transparent,
      foregroundColor: Colors.white,
      elevation: 0,
      scrolledUnderElevation: 0, // Pas de surface tint sur le gradient gold
      flexibleSpace: Container(
        decoration: const BoxDecoration(
          gradient: UnionFlowColors.goldGradient,
        ),
      ),
      leading: Builder(
        builder: (ctx) => IconButton(
          icon: const Icon(Icons.menu, size: 22, color: Colors.white),
          onPressed: () => Scaffold.of(ctx).openDrawer(),
        ),
      ),
      title: Row(
        children: [
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(6),
              border: Border.all(color: Colors.white.withOpacity(0.4)),
            ),
            alignment: Alignment.center,
            child: const Text(
              'A',
              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: Colors.white)),
              Text('Admin Organisation',
                  style: TextStyle(fontSize: 10, fontWeight: FontWeight.w400, color: Colors.white70)),
            ],
          ),
        ],
      ),
      iconTheme: const IconThemeData(color: Colors.white),
      actionsIconTheme: const IconThemeData(color: Colors.white),
      actions: [
        UnionExportButton(onExport: (_) => _handleExport(context)),
        const SizedBox(width: 8),
        UnionNotificationBadge(
          count: 0,
          child: IconButton(
            icon: const Icon(Icons.notifications_outlined, color: Colors.white),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const NotificationsPageWrapper()),
            ),
          ),
        ),
        const SizedBox(width: 8),
      ],
    );
  }

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

  static Future<void> _handleExport(BuildContext context) async {
    if (kIsWeb) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Export PDF disponible sur l\'app mobile.')),
        );
      }
      return;
    }
    final authState = context.read<AuthBloc>().state;
    if (authState is! AuthAuthenticated) return;
    final user = authState.user;
    if (user.organizationContexts.isEmpty) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Aucune organisation associée.')),
        );
      }
      return;
    }
    final orgCtx = user.organizationContexts.first;
    showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const Center(child: CircularProgressIndicator()),
    );
    try {
      final dataSource = sl<DashboardRemoteDataSource>();
      final data = await dataSource.getDashboardData(orgCtx.organizationId, user.id);
      final path = await DashboardExportService().exportDashboardReport(
        dashboardData: data,
        organizationName: orgCtx.organizationName,
        reportTitle: 'Rapport dashboard - ${DateTime.now().day}/${DateTime.now().month}/${DateTime.now().year}',
      );
      if (context.mounted) {
        Navigator.of(context).pop();
        await Share.shareXFiles([XFile(path)], text: 'Rapport UnionFlow');
      }
    } catch (e) {
      if (context.mounted) {
        Navigator.of(context).pop();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Export impossible: $e')),
        );
      }
    }
  }
}
