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 '../../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: UnionFlowColors.background,
      appBar: _buildAppBar(context),
      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;
            final orgContext = user?.organizationContexts.isNotEmpty == true
                ? user!.organizationContexts.first
                : null;

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

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

                      // Balance organisation (données backend réelles)
                      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)}% ce mois'
                              : 'Aucune variation',
                          isTrendPositive: (stats?.monthlyGrowth ?? 0) >= 0,
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Stats organisation (données backend réelles)
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 300),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionStatWidget(
                                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,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionStatWidget(
                                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,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 400),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Événements',
                                value: '${stats?.upcomingEvents ?? 0}',
                                icon: Icons.event_outlined,
                                color: UnionFlowColors.gold,
                                trend: stats?.totalEvents != null ? '${stats!.totalEvents} total' : null,
                                isTrendUp: true,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Cotisations',
                                value: '${stats?.totalContributions ?? 0}',
                                icon: Icons.trending_up,
                                color: UnionFlowColors.amber,
                                trend: _formatAmount(stats?.totalContributionAmount ?? 0),
                                isTrendUp: true,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Événements à venir (données backend)
                      if (dashboardData != null && dashboardData.hasUpcomingEvents) ...[
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 500),
                          child: const Text(
                            'Événements à Venir',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w700,
                              color: UnionFlowColors.textPrimary,
                            ),
                          ),
                        ),
                        const SizedBox(height: 16),
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 600),
                          child: Column(
                            children: dashboardData.upcomingEvents.take(3).map((event) =>
                              Container(
                                margin: const EdgeInsets.only(bottom: 12),
                                padding: const EdgeInsets.all(16),
                                decoration: BoxDecoration(
                                  color: UnionFlowColors.surface,
                                  borderRadius: BorderRadius.circular(12),
                                  border: Border.all(color: UnionFlowColors.border, width: 1),
                                  boxShadow: UnionFlowColors.softShadow,
                                ),
                                child: Row(
                                  children: [
                                    Container(
                                      width: 50,
                                      height: 50,
                                      decoration: BoxDecoration(
                                        gradient: UnionFlowColors.warmGradient,
                                        borderRadius: BorderRadius.circular(10),
                                      ),
                                      child: const Icon(
                                        Icons.event,
                                        color: Colors.white,
                                        size: 26,
                                      ),
                                    ),
                                    const SizedBox(width: 14),
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            event.title,
                                            style: const TextStyle(
                                              fontSize: 14,
                                              fontWeight: FontWeight.w600,
                                              color: UnionFlowColors.textPrimary,
                                            ),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          const SizedBox(height: 4),
                                          Text(
                                            event.formattedDate,
                                            style: const TextStyle(
                                              fontSize: 12,
                                              color: UnionFlowColors.textSecondary,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    if (event.hasParticipantInfo)
                                      Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
                                        decoration: BoxDecoration(
                                          color: UnionFlowColors.gold.withOpacity(0.1),
                                          borderRadius: BorderRadius.circular(8),
                                        ),
                                        child: Text(
                                          '${event.currentParticipants}/${event.maxParticipants}',
                                          style: const TextStyle(
                                            fontSize: 11,
                                            fontWeight: FontWeight.w700,
                                            color: UnionFlowColors.gold,
                                          ),
                                        ),
                                      ),
                                  ],
                                ),
                              )
                            ).toList(),
                          ),
                        ),
                        const SizedBox(height: 24),
                      ],

                      // Activité récente (données backend)
                      if (dashboardData != null && dashboardData.hasRecentActivity) ...[
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 520),
                          child: const Text(
                            'Activité Récente',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w700,
                              color: UnionFlowColors.textPrimary,
                            ),
                          ),
                        ),
                        const SizedBox(height: 16),
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 580),
                          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.gold.withOpacity(0.2),
                                      child: Icon(
                                        activity.type == 'member' ? Icons.person_add :
                                        activity.type == 'event' ? Icons.event :
                                        Icons.info_outline,
                                        size: 20,
                                        color: UnionFlowColors.gold,
                                      ),
                                    ),
                                    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),
                      ],

                      // Répartition actifs / inactifs (données backend)
                      if (stats != null && stats.totalMembers > 0)
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 700),
                          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: 24),

                      // Gestion
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 800),
                        child: const Text(
                          'Gestion de l\'Organisation',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w700,
                            color: UnionFlowColors.textPrimary,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 900),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionActionButton(
                                label: 'Membres',
                                icon: Icons.people,
                                onTap: () => Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder: (_) => const MembersPageWrapper(),
                                  ),
                                ),
                                backgroundColor: UnionFlowColors.unionGreen,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Finance',
                                icon: Icons.account_balance,
                                onTap: () => Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder: (_) => const CotisationsPageWrapper(),
                                  ),
                                ),
                                backgroundColor: UnionFlowColors.gold,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Événements',
                                icon: Icons.event,
                                onTap: () => Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder: (_) => const EventsPageWrapper(),
                                  ),
                                ),
                                backgroundColor: UnionFlowColors.terracotta,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Paramètres Système réservé au super admin (pas affiché pour org admin)
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 1000),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionActionButton(
                                label: 'Rapports',
                                icon: Icons.description,
                                onTap: () => Navigator.of(context).push(
                                  MaterialPageRoute(
                                    builder: (_) => const ReportsPageWrapper(),
                                  ),
                                ),
                                backgroundColor: UnionFlowColors.info,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Historique',
                                icon: Icons.history,
                                onTap: () {
                                  Navigator.of(context).push(
                                    MaterialPageRoute<void>(
                                      builder: (_) => const ReportsPageWrapper(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.amber,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: UnionFlowColors.surface,
      elevation: 0,
      title: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              gradient: UnionFlowColors.goldGradient,
              borderRadius: BorderRadius.circular(8),
            ),
            alignment: Alignment.center,
            child: const Text(
              'A',
              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(
                'Admin Organisation',
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.w400,
                  color: UnionFlowColors.textSecondary,
                ),
              ),
            ],
          ),
        ],
      ),
      iconTheme: const IconThemeData(color: UnionFlowColors.textPrimary),
      actions: [
        UnionExportButton(
          onExport: (_) => _handleExport(context),
        ),
        const SizedBox(width: 8),
        UnionNotificationBadge(
          count: 0,
          child: IconButton(
            icon: const Icon(Icons.notifications_outlined),
            color: UnionFlowColors.textPrimary,
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(
                builder: (_) => const NotificationsPageWrapper(),
              ),
            ),
          ),
        ),
        const SizedBox(width: 8),
      ],
    );
  }

  Widget _buildUserHeader(dynamic user, dynamic orgContext) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: UnionFlowColors.goldGradient,
        borderRadius: BorderRadius.circular(16),
        border: const Border(
          top: BorderSide(color: UnionFlowColors.gold, width: 3),
        ),
        boxShadow: UnionFlowColors.goldGlowShadow,
      ),
      child: Column(
        children: [
          Row(
            children: [
              CircleAvatar(
                radius: 28,
                backgroundColor: Colors.white.withOpacity(0.3),
                child: Text(
                  user?.initials ?? 'AD',
                  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 ?? 'Administrateur',
                      style: const TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w700,
                        color: Colors.white,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      orgContext?.organizationName ?? 'Organisation',
                      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(
                  'ADMIN',
                  style: TextStyle(
                    fontSize: 10,
                    fontWeight: FontWeight.w800,
                    color: UnionFlowColors.gold,
                    letterSpacing: 0.5,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  String _formatAmount(double amount) {
    if (amount >= 1000000) {
      return '${(amount / 1000000).toStringAsFixed(1)}M FCFA';
    } else 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;
    final orgId = orgCtx.organizationId;
    final orgName = orgCtx.organizationName;
    final userId = user.id;
    showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const Center(child: CircularProgressIndicator()),
    );
    try {
      final dataSource = sl<DashboardRemoteDataSource>();
      final data = await dataSource.getDashboardData(orgId, userId);
      final path = await DashboardExportService().exportDashboardReport(
        dashboardData: data,
        organizationName: orgName,
        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')),
        );
      }
    }
  }
}
