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 '../../../../authentication/presentation/bloc/auth_bloc.dart';
import '../../../../contributions/presentation/pages/contributions_page_wrapper.dart';
import '../../../../epargne/presentation/pages/epargne_page.dart';
import '../../../../profile/presentation/pages/profile_page_wrapper.dart';
import '../../../../help/presentation/pages/help_support_page.dart';
import '../../widgets/dashboard_drawer.dart';

/// Dashboard Membre Simple - Design UnionFlow
class SimpleMemberDashboard extends StatelessWidget {
  const SimpleMemberDashboard({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UnionFlowColors.background,
      appBar: _buildAppBar(),
      drawer: DashboardDrawer(
        onNavigate: (route) {
          Navigator.of(context).pushNamed(route);
        },
        onLogout: () {
          context.read<AuthBloc>().add(const AuthLogoutRequested());
        },
      ),
      body: AfricanPatternBackground(
        child: BlocBuilder<AuthBloc, AuthState>(
          builder: (context, authState) {
            final user = (authState is AuthAuthenticated) ? authState.user : null;

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

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

                return SingleChildScrollView(
                  padding: const EdgeInsets.all(24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // En-tête avec badge de rôle
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 100),
                        child: _buildUserHeader(user),
                      ),
                      const SizedBox(height: 24),

                      // Solde personnel
                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 200),
                        child: UnionBalanceCard(
                          label: 'Mon Solde',
                          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),

                      // Ma situation
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 300),
                        child: const Text(
                          'Ma Situation',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w700,
                            color: UnionFlowColors.textPrimary,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 400),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Cotisations',
                                value: stats != null && stats.totalContributions > 0 ? 'À jour' : 'En retard',
                                icon: Icons.check_circle_outline,
                                color: stats != null && stats.totalContributions > 0
                                    ? UnionFlowColors.success
                                    : UnionFlowColors.warning,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionStatWidget(
                                label: 'Événements',
                                value: '${stats?.upcomingEvents ?? 0}',
                                icon: Icons.event_outlined,
                                color: UnionFlowColors.gold,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Actions rapides
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 500),
                        child: const Text(
                          'Actions Rapides',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w700,
                            color: UnionFlowColors.textPrimary,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 600),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionActionButton(
                                label: 'Cotiser',
                                icon: Icons.payment,
                                onTap: () {
                                  Navigator.of(context).push(
                                    MaterialPageRoute<void>(
                                      builder: (_) => const CotisationsPageWrapper(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.unionGreen,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Épargner',
                                icon: Icons.savings_outlined,
                                onTap: () {
                                  Navigator.of(context).push(
                                    MaterialPageRoute<void>(
                                      builder: (_) => const EpargnePage(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.gold,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 700),
                        child: Row(
                          children: [
                            Expanded(
                              child: UnionActionButton(
                                label: 'Mes Infos',
                                icon: Icons.person_outline,
                                onTap: () {
                                  Navigator.of(context).push(
                                    MaterialPageRoute<void>(
                                      builder: (_) => const ProfilePageWrapper(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.indigo,
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: UnionActionButton(
                                label: 'Support',
                                icon: Icons.help_outline,
                                onTap: () {
                                  Navigator.of(context).push(
                                    MaterialPageRoute<void>(
                                      builder: (_) => const HelpSupportPage(),
                                    ),
                                  );
                                },
                                backgroundColor: UnionFlowColors.terracotta,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Événements à venir (données backend)
                      if (dashboardData != null && dashboardData.hasUpcomingEvents) ...[
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 800),
                          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: 900),
                          child: Column(
                            children: dashboardData.upcomingEvents.take(2).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: 48,
                                      height: 48,
                                      decoration: BoxDecoration(
                                        color: UnionFlowColors.gold.withOpacity(0.1),
                                        borderRadius: BorderRadius.circular(8),
                                      ),
                                      child: const Icon(
                                        Icons.event,
                                        color: UnionFlowColors.gold,
                                        size: 24,
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    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.daysUntilEventInt <= 7)
                                      Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                        decoration: BoxDecoration(
                                          color: UnionFlowColors.warning.withOpacity(0.1),
                                          borderRadius: BorderRadius.circular(6),
                                        ),
                                        child: Text(
                                          '${event.daysUntilEventInt}j',
                                          style: const TextStyle(
                                            fontSize: 11,
                                            fontWeight: FontWeight.w700,
                                            color: UnionFlowColors.warning,
                                          ),
                                        ),
                                      ),
                                  ],
                                ),
                              )
                            ).toList(),
                          ),
                        ),
                      ],
                    ],
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: UnionFlowColors.surface,
      elevation: 0,
      title: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              gradient: UnionFlowColors.primaryGradient,
              borderRadius: BorderRadius.circular(8),
            ),
            alignment: Alignment.center,
            child: const Text(
              'U',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w900,
                fontSize: 18,
              ),
            ),
          ),
          const SizedBox(width: 12),
          const Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                'UnionFlow',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w700,
                  color: UnionFlowColors.textPrimary,
                ),
              ),
              Text(
                'Membre Simple',
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.w400,
                  color: UnionFlowColors.textSecondary,
                ),
              ),
            ],
          ),
        ],
      ),
      iconTheme: const IconThemeData(color: UnionFlowColors.textPrimary),
    );
  }

  Widget _buildUserHeader(dynamic user) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: UnionFlowColors.subtleGradient,
        borderRadius: BorderRadius.circular(16),
        border: const Border(
          top: BorderSide(color: UnionFlowColors.unionGreen, width: 3),
        ),
        boxShadow: UnionFlowColors.softShadow,
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: 28,
            backgroundColor: UnionFlowColors.unionGreen.withOpacity(0.2),
            child: Text(
              user?.initials ?? 'M',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                color: UnionFlowColors.unionGreen,
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  user?.fullName ?? 'Membre',
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w700,
                    color: UnionFlowColors.textPrimary,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Membre depuis ${user?.createdAt.year ?? 2024}',
                  style: const TextStyle(
                    fontSize: 12,
                    color: UnionFlowColors.textSecondary,
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
            decoration: BoxDecoration(
              color: UnionFlowColors.unionGreen,
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Text(
              'MEMBRE',
              style: TextStyle(
                fontSize: 10,
                fontWeight: FontWeight.w800,
                color: Colors.white,
                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';
  }
}
