import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../features/authentication/presentation/bloc/auth_bloc.dart';
import '../../../features/profile/presentation/pages/profile_page_wrapper.dart';
import '../../../features/contributions/presentation/pages/contributions_page_wrapper.dart';
import '../../../features/solidarity/presentation/pages/demandes_aide_page_wrapper.dart';
import '../../../features/settings/presentation/pages/system_settings_page.dart';
import '../../../features/help/presentation/pages/help_support_page.dart';
import '../../../shared/design_system/unionflow_design_system.dart';
import '../../../shared/widgets/mini_avatar.dart';

/// UnionFlow Mobile - Composant DRY : Menu Profil Latéral
/// Un tiroir (drawer) de style réseau social (Twitter/Facebook) très épuré.
class ProfileDrawer extends StatelessWidget {
  const ProfileDrawer({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Drawer(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            BlocBuilder<AuthBloc, AuthState>(
              buildWhen: (prev, curr) => curr is AuthAuthenticated || prev is AuthAuthenticated,
              builder: (context, authState) {
                final user = authState is AuthAuthenticated ? authState.user : null;
                final name = user?.fullName ?? 'Utilisateur';
                final email = user?.email ?? '—';
                final initial = name.isNotEmpty ? name[0].toUpperCase() : 'U';
                return Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      MiniAvatar(fallbackText: initial, size: 48, isOnline: user != null),
                      const SizedBox(height: 12),
                      Text(
                        name,
                        style: AppTypography.headerSmall.copyWith(
                          color: isDark ? AppColors.textPrimaryDark : AppColors.textPrimary,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        email,
                        style: AppTypography.subtitleSmall,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 12),
                      Row(
                        children: [
                          Text('— ', style: AppTypography.actionText),
                          Text('Cotisations', style: AppTypography.subtitleSmall),
                          const SizedBox(width: 16),
                          Text('— ', style: AppTypography.actionText),
                          Text('Événements attendus', style: AppTypography.subtitleSmall),
                        ],
                      ),
                    ],
                  ),
                );
              },
            ),
            
            Divider(color: isDark ? AppColors.borderDark : AppColors.border, height: 1),
            
            // Liens / Actions (factorisés)
            Expanded(
              child: ListView(
                padding: const EdgeInsets.symmetric(vertical: 8),
                children: [
                  _buildDrawerItem(context, Icons.person_outline, 'Mon Profil', () { Navigator.pop(context); Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const ProfilePageWrapper())); }),
                  _buildDrawerItem(context, Icons.history, 'Historique', () { Navigator.pop(context); Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const ContributionsPageWrapper())); }),
                  _buildDrawerItem(context, Icons.favorite_border, 'Solidarité', () { Navigator.pop(context); Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const DemandesAidePageWrapper())); }),
                  _buildDrawerItem(context, Icons.settings_outlined, 'Paramètres', () { Navigator.pop(context); Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const SystemSettingsPage())); }),
                  _buildDrawerItem(context, Icons.help_outline, 'Aide & Support', () { Navigator.pop(context); Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const HelpSupportPage())); }),
                ],
              ),
            ),

            Divider(color: isDark ? AppColors.borderDark : AppColors.border, height: 1),
            
            // Bouton Déconnexion
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: InkWell(
                onTap: () {
                  context.read<AuthBloc>().add(AuthLogoutRequested());
                  Navigator.pop(context); // Fermer le drawer
                },
                child: Row(
                  children: [
                    const Icon(Icons.logout, color: AppColors.error, size: 20),
                    const SizedBox(width: 16),
                    Text(
                      'Se déconnecter',
                      style: AppTypography.actionText.copyWith(color: AppColors.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildDrawerItem(BuildContext context, IconData icon, String title, VoidCallback onTap) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 14.0),
        child: Row(
          children: [
            Icon(
              icon,
              size: 22,
              color: isDark ? AppColors.textPrimaryDark : AppColors.textPrimary,
            ),
            const SizedBox(width: 20),
            Text(
              title,
              style: AppTypography.headerSmall.copyWith(
                fontWeight: FontWeight.w500,
                color: isDark ? AppColors.textPrimaryDark : AppColors.textPrimary,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
