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

import '../../features/authentication/presentation/bloc/auth_bloc.dart';
import '../../features/authentication/data/models/user_role.dart';
import '../../shared/design_system/unionflow_design_system.dart';
import '../../features/dashboard/presentation/pages/role_dashboards/role_dashboards.dart';
import '../../features/members/presentation/pages/members_page_wrapper.dart';
import '../../features/events/presentation/pages/events_page_wrapper.dart';
import '../../features/contributions/presentation/pages/contributions_page_wrapper.dart';

import '../../features/about/presentation/pages/about_page.dart';
import '../../features/help/presentation/pages/help_support_page.dart';
import '../../features/notifications/presentation/pages/notifications_page.dart';
import '../../features/profile/presentation/pages/profile_page.dart';
import '../../features/settings/presentation/pages/system_settings_page.dart';
import '../../features/backup/presentation/pages/backup_page.dart';
import '../../features/logs/presentation/pages/logs_page.dart';
import '../../features/reports/presentation/pages/reports_page.dart';

/// Layout principal avec navigation hybride
/// Bottom Navigation pour les sections principales + Drawer pour fonctions avancées
class MainNavigationLayout extends StatefulWidget {
  const MainNavigationLayout({super.key});

  @override
  State<MainNavigationLayout> createState() => _MainNavigationLayoutState();
}

class _MainNavigationLayoutState extends State<MainNavigationLayout> {
  int _selectedIndex = 0;

  /// Obtient le dashboard approprié selon le rôle de l'utilisateur
  Widget _getDashboardForRole(UserRole role) {
    switch (role) {
      case UserRole.superAdmin:
        return const SuperAdminDashboard();
      case UserRole.orgAdmin:
        return const OrgAdminDashboard();
      case UserRole.moderator:
        return const ModeratorDashboard();
      case UserRole.activeMember:
        return const ActiveMemberDashboard();
      case UserRole.simpleMember:
        return const SimpleMemberDashboard();
      case UserRole.visitor:
        return const VisitorDashboard();
    }
  }

  List<Widget> _getPages(UserRole role) {
    return [
      _getDashboardForRole(role),
      const MembersPageWrapper(), // Wrapper BLoC pour connexion API
      const EventsPageWrapper(), // Wrapper BLoC pour connexion API
      const MorePage(), // Page "Plus" qui affiche les options avancées
    ];
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AuthBloc, AuthState>(
      builder: (context, state) {
        if (state is! AuthAuthenticated) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        return Scaffold(
          backgroundColor: ColorTokens.background,
          body: SafeArea(
            top: true, // Respecte le StatusBar
            bottom: false, // Le BottomNavigationBar gère son propre SafeArea
            child: IndexedStack(
              index: _selectedIndex,
              children: _getPages(state.effectiveRole),
            ),
          ),
          bottomNavigationBar: SafeArea(
            top: false,
            child: Container(
              decoration: const BoxDecoration(
                color: ColorTokens.surface,
                boxShadow: [
                  BoxShadow(
                    color: ColorTokens.shadow,
                    blurRadius: 8,
                    offset: Offset(0, -2),
                  ),
                ],
              ),
              child: BottomNavigationBar(
                type: BottomNavigationBarType.fixed,
                currentIndex: _selectedIndex,
                onTap: (index) {
                  setState(() {
                    _selectedIndex = index;
                  });
                },
                backgroundColor: ColorTokens.surface,
                selectedItemColor: ColorTokens.primary,
                unselectedItemColor: ColorTokens.onSurfaceVariant,
                selectedLabelStyle: TypographyTokens.labelSmall.copyWith(
                  fontWeight: FontWeight.w600,
                ),
                unselectedLabelStyle: TypographyTokens.labelSmall,
                elevation: 0, // Géré par le Container
                items: const [
                  BottomNavigationBarItem(
                    icon: Icon(Icons.dashboard_outlined),
                    activeIcon: Icon(Icons.dashboard),
                    label: 'Dashboard',
                  ),
                  BottomNavigationBarItem(
                    icon: Icon(Icons.people_outline),
                    activeIcon: Icon(Icons.people),
                    label: 'Membres',
                  ),
                  BottomNavigationBarItem(
                    icon: Icon(Icons.event_outlined),
                    activeIcon: Icon(Icons.event),
                    label: 'Événements',
                  ),
                  BottomNavigationBarItem(
                    icon: Icon(Icons.more_horiz_outlined),
                    activeIcon: Icon(Icons.more_horiz),
                    label: 'Plus',
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

/// Page "Plus" avec les fonctions avancées selon le rôle
class MorePage extends StatelessWidget {
  const MorePage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AuthBloc, AuthState>(
      builder: (context, state) {
        if (state is! AuthAuthenticated) {
          return Container(
            color: const Color(0xFFF8F9FA),
            child: const Center(child: CircularProgressIndicator()),
          );
        }

        return Container(
          color: ColorTokens.background,
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(SpacingTokens.lg),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Titre de la section
                Text(
                  'Plus d\'Options',
                  style: TypographyTokens.headlineMedium.copyWith(
                    color: ColorTokens.primary,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: SpacingTokens.lg),

                // Profil utilisateur
                _buildUserProfile(state),
                const SizedBox(height: 16),

                // Options selon le rôle
                ..._buildRoleBasedOptions(context, state),

                const SizedBox(height: 16),

                // Options communes
                ..._buildCommonOptions(context),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildUserProfile(AuthAuthenticated state) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: const Color(0xFF6C5CE7),
              borderRadius: BorderRadius.circular(25),
            ),
            child: Center(
              child: Text(
                state.user.firstName.isNotEmpty ? state.user.firstName[0].toUpperCase() : 'U',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '${state.user.firstName} ${state.user.lastName}',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF374151),
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  state.effectiveRole.displayName,
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xFF6C5CE7),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  state.user.email,
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFF6B7280),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  List<Widget> _buildRoleBasedOptions(BuildContext context, AuthAuthenticated state) {
    final options = <Widget>[];

    // Options Super Admin uniquement
    if (state.effectiveRole == UserRole.superAdmin) {
      options.addAll([
        _buildSectionTitle('Administration Système'),
        _buildOptionTile(
          icon: Icons.settings,
          title: 'Paramètres Système',
          subtitle: 'Configuration globale',
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => const SystemSettingsPage(),
              ),
            );
          },
        ),
        _buildOptionTile(
          icon: Icons.backup,
          title: 'Sauvegarde & Restauration',
          subtitle: 'Gestion des sauvegardes',
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => const BackupPage(),
              ),
            );
          },
        ),
        _buildOptionTile(
          icon: Icons.article,
          title: 'Logs & Monitoring',
          subtitle: 'Surveillance et journaux',
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => const LogsPage(),
              ),
            );
          },
        ),
      ]);
    }

    // Options Admin+ (Admin Organisation et Super Admin)
    if (state.effectiveRole == UserRole.orgAdmin || state.effectiveRole == UserRole.superAdmin) {
      options.addAll([
        _buildSectionTitle('Rapports & Analytics'),
        _buildOptionTile(
          icon: Icons.assessment,
          title: 'Rapports & Analytics',
          subtitle: 'Statistiques détaillées',
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => const ReportsPage(),
              ),
            );
          },
        ),
      ]);
    }

    return options;
  }

  List<Widget> _buildCommonOptions(BuildContext context) {
    return [
      _buildSectionTitle('Général'),
      _buildOptionTile(
        icon: Icons.payment,
        title: 'Cotisations',
        subtitle: 'Gérer les cotisations',
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const CotisationsPageWrapper(),
            ),
          );
        },
      ),
      _buildOptionTile(
        icon: Icons.person,
        title: 'Mon Profil',
        subtitle: 'Modifier mes informations',
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const ProfilePage(),
            ),
          );
        },
      ),
      _buildOptionTile(
        icon: Icons.notifications,
        title: 'Notifications',
        subtitle: 'Gérer les notifications',
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const NotificationsPage(),
            ),
          );
        },
      ),
      _buildOptionTile(
        icon: Icons.help,
        title: 'Aide & Support',
        subtitle: 'Documentation et support',
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const HelpSupportPage(),
            ),
          );
        },
      ),
      _buildOptionTile(
        icon: Icons.info,
        title: 'À propos',
        subtitle: 'Version et informations',
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const AboutPage(),
            ),
          );
        },
      ),
      const SizedBox(height: 16),
      _buildOptionTile(
        icon: Icons.logout,
        title: 'Déconnexion',
        subtitle: 'Se déconnecter de l\'application',
        color: Colors.red,
        onTap: () {
          context.read<AuthBloc>().add(const AuthLogoutRequested());
        },
      ),
    ];
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.only(
        top: 16,
        bottom: 8,
      ),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: Color(0xFF6C5CE7),
        ),
      ),
    );
  }

  Widget _buildOptionTile({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
    Color? color,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: (color ?? const Color(0xFF6C5CE7)).withOpacity(0.1),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Icon(
                  icon,
                  color: color ?? const Color(0xFF6C5CE7),
                  size: 20,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: color ?? const Color(0xFF374151),
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      subtitle,
                      style: const TextStyle(
                        fontSize: 12,
                        color: Color(0xFF6B7280),
                      ),
                    ),
                  ],
                ),
              ),
              const Icon(
                Icons.chevron_right,
                color: Color(0xFF6B7280),
                size: 16,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
