import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:travel_mate/blocs/trip/trip_bloc.dart';
import 'package:travel_mate/blocs/trip/trip_event.dart';
import '../components/home/home_content.dart';
import '../components/settings/settings_content.dart';
import '../components/map/map_content.dart';
import '../components/group/group_content.dart';
import '../components/account/account_content.dart';
import '../blocs/user/user_bloc.dart';
import '../blocs/user/user_event.dart';
import '../blocs/auth/auth_bloc.dart';
import '../blocs/auth/auth_event.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  final Map<int, Widget> _pageCache = {};

  final List<String> titles = [
    'Mes voyages',
    'Paramètres',
    'Carte',
    'Chat de groupe',
    'Comptes',
  ];

  @override
  void initState() {
    super.initState();
    // Initialiser les données utilisateur
    context.read<UserBloc>().add(UserInitialized());
  }

  Widget _buildPage(int index) {
    if (_pageCache.containsKey(index)) {
      return _pageCache[index]!;
    }

    Widget page;
    switch (index) {
      case 0:
        page = const HomeContent();
        break;
      case 1:
        page = const SettingsContent();
        break;
      case 2:
        page = const MapContent();
        break;
      case 3:
        page = const GroupContent();
        break;
      case 4:
        page = const AccountContent();
        break;
      default:
        page = const HomeContent();
    }

    _pageCache[index] = page;
    return page;
  }

  void _onNavigationTap(int index) {
    setState(() {
      _currentIndex = index;
    });
    Navigator.pop(context);
  }

  // Nouvelle méthode pour gérer la déconnexion proprement
  Future<void> _handleLogout() async {
    // Fermer le drawer
    Navigator.pop(context);

    // Afficher un dialog de confirmation
    final shouldLogout = await showDialog<bool>(
      context: context,
      builder: (BuildContext dialogContext) {
        return AlertDialog(
          title: const Text('Déconnexion'),
          content: const Text('Êtes-vous sûr de vouloir vous déconnecter ?'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(dialogContext, false),
              child: const Text('Annuler'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.pop(dialogContext, true),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
                foregroundColor: Colors.white,
              ),
              child: const Text('Déconnexion'),
            ),
          ],
        );
      },
    );

    if (shouldLogout != true || !mounted) return;
    try {
      context.read<TripBloc>().add(ResetTrips());
      context.read<UserBloc>().add(UserLoggedOut());
      _pageCache.clear();
      context.read<AuthBloc>().add(AuthSignOutRequested());
      await Future.delayed(const Duration(milliseconds: 150));
      if (!mounted) return;
      Navigator.of(context).pushNamedAndRemoveUntil(
        '/login',
        (Route<dynamic> route) => false, // Supprime TOUTES les routes
      );
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Erreur lors de la déconnexion: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(titles[_currentIndex]),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        foregroundColor: Colors.white,
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            DrawerHeader(
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.inversePrimary,
              ),
              child: const Text(
                "Travel Mate",
                style: TextStyle(color: Colors.white, fontSize: 24),
              ),
            ),
            _buildDrawerItem(icon: Icons.home, title: "Mes voyages", index: 0),
            _buildDrawerItem(icon: Icons.settings, title: "Paramètres", index: 1),
            _buildDrawerItem(icon: Icons.map, title: "Carte", index: 2),
            _buildDrawerItem(icon: Icons.group, title: "Chat de groupe", index: 3),
            _buildDrawerItem(icon: Icons.account_balance_wallet, title: "Comptes", index: 4),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.logout, color: Colors.red),
              title: const Text("Déconnexion", style: TextStyle(color: Colors.red)),
              onTap: _handleLogout, // Utiliser la nouvelle méthode
            ),
          ],
        ),
      ),
      body: IndexedStack(
        index: _currentIndex,
        children: [
          for (int i = 0; i < titles.length; i++)
            if (_currentIndex == i || _pageCache.containsKey(i))
              _buildPage(i)
            else
              Container(),
        ],
      ),
    );
  }

  Widget _buildDrawerItem({
    required IconData icon,
    required String title,
    required int index,
  }) {
    return ListTile(
      leading: Icon(icon),
      title: Text(title),
      selected: _currentIndex == index,
      selectedTileColor: Theme.of(context).colorScheme.primary.withValues(alpha: 0.1),
      onTap: () => _onNavigationTap(index),
    );
  }

  @override
  void dispose() {
    _pageCache.clear();
    super.dispose();
  }
}