/// Widget de menu latéral (drawer) du dashboard
/// Navigation principale de l'application
library dashboard_drawer;

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

import '../../../../shared/design_system/unionflow_design_system.dart';
import '../../../../shared/widgets/core_card.dart';
import '../../../../shared/widgets/mini_avatar.dart';

import '../../../authentication/presentation/bloc/auth_bloc.dart';

import '../../../profile/presentation/pages/profile_page_wrapper.dart';
import '../../../notifications/presentation/pages/notifications_page_wrapper.dart';
import '../../../help/presentation/pages/help_support_page.dart';
import '../../../about/presentation/pages/about_page.dart';

/// Widget de menu latéral (Drawer / Hamburger)
///
/// Accessible via le bouton hamburger de l'AppBar.
/// Contient uniquement les menus « Mon Espace » :
/// - Mon Profil
/// - Notifications
/// - Aide & Support
/// - À propos
/// - Déconnexion
class DashboardDrawer extends StatelessWidget {
  /// Callback pour les actions de navigation nommée (optionnel, non utilisé en interne)
  final Function(String route)? onNavigate;

  /// Callback pour la déconnexion
  final VoidCallback? onLogout;

  const DashboardDrawer({
    super.key,
    this.onNavigate,
    this.onLogout,
  });

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AuthBloc, AuthState>(
      builder: (context, authState) {
        if (authState is! AuthAuthenticated) {
          return const Drawer();
        }

        final state = authState;

        return Drawer(
          backgroundColor: ColorTokens.background,
          child: SafeArea(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // ── En-tête utilisateur (même style que MorePage) ──────────────
                  _buildUserProfile(state),
                  const SizedBox(height: SpacingTokens.md),

                  // ── Section Mon Espace ─────────────────────────────────────────
                  _buildSectionTitle('Mon Espace'),

                  _buildOptionTile(
                    context: context,
                    icon: Icons.person,
                    title: 'Mon Profil',
                    subtitle: 'Modifier mes informations',
                    onTap: () => Navigator.of(context).push(
                      MaterialPageRoute(builder: (_) => const ProfilePageWrapper()),
                    ),
                  ),
                  _buildOptionTile(
                    context: context,
                    icon: Icons.notifications,
                    title: 'Notifications',
                    subtitle: 'Gérer les notifications',
                    onTap: () => Navigator.of(context).push(
                      MaterialPageRoute(builder: (_) => const NotificationsPageWrapper()),
                    ),
                  ),
                  _buildOptionTile(
                    context: context,
                    icon: Icons.help,
                    title: 'Aide & Support',
                    subtitle: 'Documentation et support',
                    onTap: () => Navigator.of(context).push(
                      MaterialPageRoute(builder: (_) => const HelpSupportPage()),
                    ),
                  ),
                  _buildOptionTile(
                    context: context,
                    icon: Icons.info,
                    title: 'À propos',
                    subtitle: 'Version et informations',
                    onTap: () => Navigator.of(context).push(
                      MaterialPageRoute(builder: (_) => const AboutPage()),
                    ),
                  ),

                  const SizedBox(height: SpacingTokens.md),

                  // ── Déconnexion ───────────────────────────────────────────────
                  _buildOptionTile(
                    context: context,
                    icon: Icons.logout,
                    title: 'Déconnexion',
                    subtitle: 'Se déconnecter de l\'application',
                    color: ColorTokens.error,
                    onTap: () {
                      Navigator.pop(context);
                      context.read<AuthBloc>().add(const AuthLogoutRequested());
                    },
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  // ── Profil utilisateur (idem MorePage._buildUserProfile) ──────────────────
  Widget _buildUserProfile(AuthAuthenticated state) {
    return CoreCard(
      child: Row(
        children: [
          MiniAvatar(
            fallbackText:
                state.user.firstName.isNotEmpty ? state.user.firstName[0].toUpperCase() : 'U',
            size: 40,
            imageUrl: state.user.avatar,
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '${state.user.firstName} ${state.user.lastName}',
                  style: AppTypography.actionText,
                ),
                Text(
                  state.effectiveRole.displayName.toUpperCase(),
                  style: AppTypography.badgeText.copyWith(
                    color: AppColors.primaryGreen,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  state.user.email,
                  style: AppTypography.subtitleSmall,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ── Titre de section (idem MorePage._buildSectionTitle) ───────────────────
  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.only(top: 24, bottom: 8, left: 4),
      child: Text(
        title.toUpperCase(),
        style: AppTypography.subtitleSmall.copyWith(
          fontWeight: FontWeight.bold,
          letterSpacing: 1.1,
          color: AppColors.textSecondaryLight,
        ),
      ),
    );
  }

  // ── Tuile d'option (idem MorePage._buildOptionTile) ───────────────────────
  Widget _buildOptionTile({
    required BuildContext context,
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
    Color? color,
  }) {
    final effectiveColor = color ?? AppColors.primaryGreen;

    return CoreCard(
      margin: const EdgeInsets.only(bottom: 8),
      onTap: onTap,
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: effectiveColor.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              icon,
              color: effectiveColor,
              size: 20,
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: AppTypography.actionText.copyWith(
                    color: color ?? AppColors.textPrimaryLight,
                  ),
                ),
                Text(
                  subtitle,
                  style: AppTypography.subtitleSmall,
                ),
              ],
            ),
          ),
          Icon(
            Icons.chevron_right,
            color: AppColors.textSecondaryLight,
            size: 16,
          ),
        ],
      ),
    );
  }
}
