import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; // Pour ThemeProvider
import 'package:afterwork/presentation/screens/event/event_screen.dart';
import 'package:afterwork/presentation/screens/profile/profile_screen.dart';
import 'package:afterwork/presentation/screens/social/social_screen.dart';
import 'package:afterwork/presentation/screens/establishments/establishments_screen.dart';
import 'package:afterwork/presentation/screens/home/home_content.dart';
import 'package:afterwork/data/datasources/event_remote_data_source.dart';
import 'package:afterwork/presentation/screens/notifications/notifications_screen.dart'; // Écran de notifications
import '../../../core/constants/colors.dart';
import '../../../core/theme/theme_provider.dart';
import '../friends/friends_screen.dart'; // Écran des amis

class HomeScreen extends StatefulWidget {
  final EventRemoteDataSource eventRemoteDataSource;
  final String userId;
  final String userName;
  final String userLastName;
  final String userProfileImage; // Image de profil de l'utilisateur

  const HomeScreen({
    Key? key,
    required this.eventRemoteDataSource,
    required this.userId,
    required this.userName,
    required this.userLastName,
    required this.userProfileImage, // Passer l'image de profil ici
  }) : super(key: key);

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

class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 6, vsync: this); // Ajouter un onglet pour les notifications
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  void _onMenuSelected(BuildContext context, String option) {
    switch (option) {
      case 'Publier':
        print('Publier sélectionné');
        break;
      case 'Story':
        print('Story sélectionné');
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    // Accès au ThemeProvider
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              backgroundColor: AppColors.backgroundColor,
              floating: true,
              pinned: true,
              snap: true,
              elevation: 2,
              leading: Padding(
                padding: const EdgeInsets.all(4.0), // Ajustement du padding
                child: Image.asset(
                  'lib/assets/images/logo.png',
                  height: 40, // Taille ajustée du logo
                ),
              ),
              actions: [
                _buildActionIcon(Icons.add, 'Publier', context),
                _buildActionIcon(Icons.search, 'Rechercher', context),
                _buildActionIcon(Icons.message, 'Message', context),
                _buildNotificationsIcon(context, 5), // Gérer la logique des notifications ici

                // Bouton pour basculer entre les thèmes
                Switch(
                  value: themeProvider.isDarkMode,
                  onChanged: (value) {
                    themeProvider.toggleTheme(); // Changer le thème
                  },
                  activeColor: AppColors.accentColor,
                ),
              ],
              bottom: TabBar(
                controller: _tabController,
                indicatorColor: AppColors.lightPrimary,
                labelStyle: const TextStyle(
                  fontSize: 12, // Taille réduite du texte
                  fontWeight: FontWeight.w500,
                ),
                unselectedLabelStyle: const TextStyle(
                  fontSize: 11, // Taille ajustée pour les onglets non sélectionnés
                ),
                labelColor: AppColors.lightPrimary,
                unselectedLabelColor: AppColors.iconSecondary,

                tabs: [
                  const Tab(icon: Icon(Icons.home, size: 24), text: 'Accueil'),
                  const Tab(icon: Icon(Icons.event, size: 24), text: 'Événements'),
                  const Tab(icon: Icon(Icons.location_city, size: 24), text: 'Établissements'),
                  const Tab(icon: Icon(Icons.people, size: 24), text: 'Social'),
                  const Tab(icon: Icon(Icons.people_alt_outlined, size: 24), text: 'Ami(e)s'),
                  _buildProfileTab(), // Onglet profil
                ],
              ),
            ),
          ];
        },
        body: TabBarView(
          controller: _tabController,
          children: [
            const HomeContentScreen(),
            EventScreen(
              userId: widget.userId,
              userName: widget.userName,
              userLastName: widget.userLastName,
            ),
            const EstablishmentsScreen(),
            const SocialScreen(),
            FriendsScreen(userId: widget.userId), // Correction ici : passer l'userId
            const ProfileScreen(),
          ],
        ),
      ),
    );
  }

  // Widget pour l'affichage de la photo de profil dans l'onglet
  Tab _buildProfileTab() {
    return Tab(
      child: Container(
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(
            color: Colors.blue,
            width: 2.0,
          ),
        ),
        child: CircleAvatar(
          radius: 16,
          backgroundColor: Colors.grey[200], // Couleur de fond par défaut
          child: ClipOval(
            child: FadeInImage.assetNetwork(
              placeholder: 'lib/assets/images/user_placeholder.png',
              image: widget.userProfileImage,
              fit: BoxFit.cover,
              imageErrorBuilder: (context, error, stackTrace) {
                return Image.asset('lib/assets/images/profile_picture.png', fit: BoxFit.cover);
              },
            ),
          ),
        ),
      ),
    );
  }

  // Icône pour les notifications avec un badge
  Widget _buildNotificationsIcon(BuildContext context, int notificationCount) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 6.0),
      child: Stack(
        clipBehavior: Clip.none, // Permet d'afficher le badge en dehors des limites
        children: [
          CircleAvatar(
            backgroundColor: AppColors.surface,
            radius: 18,
            child: IconButton(
              icon: const Icon(Icons.notifications, color: AppColors.darkOnPrimary, size: 20),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const NotificationsScreen(),
                  ),
                );
              },
            ),
          ),
          if (notificationCount > 0)
            Positioned(
              right: -6,
              top: -6,
              child: Container(
                padding: const EdgeInsets.all(2),
                decoration: const BoxDecoration(
                  color: Colors.red,
                  shape: BoxShape.circle,
                ),
                constraints: const BoxConstraints(
                  minWidth: 18,
                  minHeight: 18,
                ),
                child: Text(
                  notificationCount > 99 ? '99+' : '$notificationCount',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 10,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
        ],
      ),
    );
  }

  // Icône d'action générique
  Widget _buildActionIcon(IconData iconData, String label, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 6.0),
      child: CircleAvatar(
        backgroundColor: AppColors.surface,
        radius: 18,
        child: IconButton(
          icon: Icon(iconData, color: AppColors.darkOnPrimary, size: 20),
          onPressed: () {
            _onMenuSelected(context, label);
          },
        ),
      ),
    );
  }
}
