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: 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;

            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 RefreshIndicator(
                  color: UnionFlowColors.unionGreen,
                  onRefresh: () async {
                    final orgCtx = user?.organizationContexts.isNotEmpty == true
                        ? user!.organizationContexts.first : null;
                    context.read<DashboardBloc>().add(LoadDashboardData(
                      organizationId: orgCtx?.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 avec badge de rôle
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 100),
                        child: UserIdentityCard(
                          initials: user?.initials ?? 'M',
                          name: user?.fullName ?? 'Membre',
                          subtitle: 'Membre depuis ${user?.createdAt.year ?? 2024}',
                          badgeLabel: 'MEMBRE',
                          gradient: UnionFlowColors.subtleGradient,
                          accentColor: UnionFlowColors.unionGreen,
                          lightBackground: true,
                        ),
                      ),
                      const SizedBox(height: 12),

                      // 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)}%'
                              : null,
                          isTrendPositive: (stats?.monthlyGrowth ?? 0) >= 0,
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Ma Situation
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 300),
                        child: const UFSectionHeader('Ma Situation'),
                      ),
                      const SizedBox(height: 8),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 400),
                        child: GridView.count(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          crossAxisCount: 2,
                          mainAxisSpacing: 6,
                          crossAxisSpacing: 6,
                          childAspectRatio: 2.0,
                          children: [
                            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,
                            ),
                            UnionStatWidget(
                              label: 'Événements',
                              value: '${stats?.upcomingEvents ?? 0}',
                              icon: Icons.event_outlined,
                              color: UnionFlowColors.gold,
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 12),

                      // Actions rapides
                      AnimatedFadeIn(
                        delay: const Duration(milliseconds: 500),
                        child: const UFSectionHeader('Actions Rapides'),
                      ),
                      const SizedBox(height: 8),

                      AnimatedSlideIn(
                        delay: const Duration(milliseconds: 600),
                        child: GridView.count(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          crossAxisCount: 2,
                          mainAxisSpacing: 6,
                          crossAxisSpacing: 6,
                          childAspectRatio: 2.8,
                          children: [
                            UnionActionButton(
                              label: 'Cotiser',
                              icon: Icons.payment,
                              iconColor: UnionFlowColors.unionGreen,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const CotisationsPageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Épargner',
                              icon: Icons.savings_outlined,
                              iconColor: UnionFlowColors.gold,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const EpargnePage())),
                            ),
                            UnionActionButton(
                              label: 'Mes Infos',
                              icon: Icons.person_outline,
                              iconColor: UnionFlowColors.indigo,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const ProfilePageWrapper())),
                            ),
                            UnionActionButton(
                              label: 'Support',
                              icon: Icons.help_outline,
                              iconColor: UnionFlowColors.terracotta,
                              onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => const HelpSupportPage())),
                            ),
                          ],
                        ),
                      ),

                      // Événements à venir
                      if (dashboardData != null && dashboardData.hasUpcomingEvents) ...[
                        const SizedBox(height: 12),
                        AnimatedFadeIn(
                          delay: const Duration(milliseconds: 800),
                          child: UFSectionHeader(
                            'Événements à Venir',
                            trailing: '${dashboardData.upcomingEvents.length} programmés',
                          ),
                        ),
                        const SizedBox(height: 8),
                        AnimatedSlideIn(
                          delay: const Duration(milliseconds: 900),
                          child: Column(
                            children: dashboardData.upcomingEvents.take(2).map((event) =>
                              DashboardEventRow(
                                title: event.title,
                                date: event.formattedDate,
                                daysUntil: event.daysUntilEventInt <= 7 ? '${event.daysUntilEventInt}j' : null,
                              ),
                            ).toList(),
                          ),
                        ),
                      ],
                    ],
                  ),
                ),  // SingleChildScrollView
                );  // RefreshIndicator
              },
            );
          },
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: Theme.of(context).colorScheme.surface,
      elevation: 0,
      scrolledUnderElevation: 1,
      shadowColor: Theme.of(context).colorScheme.outline.withOpacity(0.2),
      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),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('UnionFlow', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: Theme.of(context).colorScheme.onSurface)),
              Text('Membre Simple', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w400, color: Theme.of(context).colorScheme.onSurfaceVariant)),
            ],
          ),
        ],
      ),
      iconTheme: IconThemeData(color: Theme.of(context).colorScheme.onSurface),
    );
  }

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