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

import '../../../core/constants/design_system.dart';
import '../../../core/theme/theme_provider.dart';
import '../../../core/utils/page_transitions.dart';
import '../../../data/datasources/event_remote_data_source.dart';
import '../../../data/services/notification_service.dart';
import '../../widgets/custom_snackbar.dart';
import '../../widgets/notification_badge.dart';
import '../chat/conversations_screen.dart';
import '../establishments/establishments_screen.dart';
import '../event/event_screen.dart';
import '../friends/friends_screen.dart';
import '../notifications/notifications_screen.dart';
import '../profile/profile_screen.dart';
import '../social/social_screen.dart';
import 'home_content.dart';

/// Écran principal de l'application avec navigation moderne.
class HomeScreen extends StatefulWidget {
  const HomeScreen({
    required this.eventRemoteDataSource,
    required this.userId,
    required this.userFirstName,
    required this.userLastName,
    required this.userProfileImage,
    super.key,
  });

  final EventRemoteDataSource eventRemoteDataSource;
  final String userId;
  final String userFirstName;
  final String userLastName;
  final String userProfileImage;

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _currentIndex = 0;

  late final List<Widget> _screens;

  @override
  void initState() {
    super.initState();
    _screens = [
      const HomeContentScreen(),
      EventScreen(
        userId: widget.userId,
        userFirstName: widget.userFirstName,
        userLastName: widget.userLastName,
        profileImageUrl: widget.userProfileImage,
      ),
      const SocialScreen(),
      FriendsScreen(userId: widget.userId),
      const ProfileScreen(),
    ];
  }

  void _onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      appBar: _buildModernAppBar(context, theme, themeProvider),
      body: IndexedStack(
        index: _currentIndex,
        children: _screens,
      ),
      bottomNavigationBar: _buildBottomNavBar(theme),
    );
  }

  /// AppBar moderne et épurée
  PreferredSizeWidget _buildModernAppBar(
    BuildContext context,
    ThemeData theme,
    ThemeProvider themeProvider,
  ) {
    return AppBar(
      elevation: 0,
      scrolledUnderElevation: 2,
      centerTitle: false,
      title: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset(
            'lib/assets/images/logo.png',
            height: 32,
            errorBuilder: (context, error, stackTrace) {
              return Icon(
                Icons.event_available,
                size: 28,
                color: theme.colorScheme.primary,
              );
            },
          ),
          const SizedBox(width: DesignSystem.spacingSm),
          Text(
            'Afterwork',
            style: theme.textTheme.titleLarge?.copyWith(
              fontWeight: FontWeight.bold,
              letterSpacing: -0.5,
            ),
          ),
        ],
      ),
      actions: [
        // Recherche
        IconButton(
          icon: const Icon(Icons.search_rounded, size: 22),
          tooltip: 'Rechercher',
          onPressed: () {
            context.showInfo('Recherche à venir');
          },
        ),

        // Messages
        IconButton(
          icon: const Icon(Icons.chat_bubble_outline_rounded, size: 22),
          tooltip: 'Messages',
          onPressed: () {
            context.pushFadeScale(const ConversationsScreen());
          },
        ),

        // Notifications avec badge
        Consumer<NotificationService>(
          builder: (context, notificationService, child) {
            return Padding(
              padding: const EdgeInsets.only(right: 4),
              child: NotificationBadge(
                count: notificationService.unreadCount,
                child: IconButton(
                  icon: const Icon(Icons.notifications_none_rounded, size: 22),
                  tooltip: 'Notifications',
                  onPressed: () {
                    context.pushFadeScale(const NotificationsScreen());
                  },
                ),
              ),
            );
          },
        ),

        // Menu établissements
        PopupMenuButton<String>(
          icon: const Icon(Icons.more_vert_rounded, size: 22),
          offset: const Offset(0, 48),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(DesignSystem.radiusMd),
          ),
          onSelected: (value) {
            switch (value) {
              case 'establishments':
                context.pushFadeScale(const EstablishmentsScreen());
                break;
              case 'theme':
                themeProvider.toggleTheme();
                break;
              case 'settings':
                context.showInfo('Paramètres à venir');
                break;
            }
          },
          itemBuilder: (context) => [
            PopupMenuItem(
              value: 'establishments',
              child: Row(
                children: [
                  Icon(
                    Icons.location_city_rounded,
                    size: 20,
                    color: theme.colorScheme.onSurface,
                  ),
                  const SizedBox(width: DesignSystem.spacingSm),
                  const Text('Établissements'),
                ],
              ),
            ),
            const PopupMenuDivider(),
            PopupMenuItem(
              value: 'theme',
              child: Row(
                children: [
                  Icon(
                    themeProvider.isDarkMode
                        ? Icons.light_mode_rounded
                        : Icons.dark_mode_rounded,
                    size: 20,
                    color: theme.colorScheme.onSurface,
                  ),
                  const SizedBox(width: DesignSystem.spacingSm),
                  Text(themeProvider.isDarkMode ? 'Mode clair' : 'Mode sombre'),
                ],
              ),
            ),
            PopupMenuItem(
              value: 'settings',
              child: Row(
                children: [
                  Icon(
                    Icons.settings_rounded,
                    size: 20,
                    color: theme.colorScheme.onSurface,
                  ),
                  const SizedBox(width: DesignSystem.spacingSm),
                  const Text('Paramètres'),
                ],
              ),
            ),
          ],
        ),
        const SizedBox(width: 4),
      ],
    );
  }

  /// BottomNavigationBar moderne
  Widget _buildBottomNavBar(ThemeData theme) {
    return Container(
      decoration: BoxDecoration(
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: NavigationBar(
        selectedIndex: _currentIndex,
        onDestinationSelected: _onTabTapped,
        elevation: 0,
        height: 64,
        labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected,
        animationDuration: const Duration(milliseconds: 400),
        destinations: [
          NavigationDestination(
            icon: const Icon(Icons.home_outlined, size: 24),
            selectedIcon: Icon(
              Icons.home_rounded,
              size: 26,
              color: theme.colorScheme.primary,
            ),
            label: 'Accueil',
          ),
          NavigationDestination(
            icon: const Icon(Icons.event_outlined, size: 24),
            selectedIcon: Icon(
              Icons.event_rounded,
              size: 26,
              color: theme.colorScheme.primary,
            ),
            label: 'Événements',
          ),
          NavigationDestination(
            icon: const Icon(Icons.explore_outlined, size: 24),
            selectedIcon: Icon(
              Icons.explore_rounded,
              size: 26,
              color: theme.colorScheme.primary,
            ),
            label: 'Social',
          ),
          NavigationDestination(
            icon: const Icon(Icons.people_outline_rounded, size: 24),
            selectedIcon: Icon(
              Icons.people_rounded,
              size: 26,
              color: theme.colorScheme.primary,
            ),
            label: 'Amis',
          ),
          NavigationDestination(
            icon: Hero(
              tag: 'user_profile_avatar_${widget.userId}',
              child: CircleAvatar(
                radius: 14,
                backgroundImage: widget.userProfileImage.isNotEmpty
                    ? NetworkImage(widget.userProfileImage)
                    : null,
                child: widget.userProfileImage.isEmpty
                    ? const Icon(Icons.person, size: 16)
                    : null,
              ),
            ),
            selectedIcon: Hero(
              tag: 'user_profile_avatar_${widget.userId}',
              child: Container(
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: theme.colorScheme.primary,
                    width: 2,
                  ),
                ),
                child: CircleAvatar(
                  radius: 14,
                  backgroundImage: widget.userProfileImage.isNotEmpty
                      ? NetworkImage(widget.userProfileImage)
                      : null,
                  child: widget.userProfileImage.isEmpty
                      ? const Icon(Icons.person, size: 16)
                      : null,
                ),
              ),
            ),
            label: 'Profil',
          ),
        ],
      ),
    );
  }
}
