import 'package:afterwork/config/router.dart';
import 'package:afterwork/data/datasources/event_remote_data_source.dart';
import 'package:afterwork/data/providers/user_provider.dart';
import 'package:afterwork/data/repositories/friends_repository_impl.dart';
import 'package:afterwork/data/services/preferences_helper.dart';
import 'package:afterwork/data/services/secure_storage.dart';
import 'package:afterwork/presentation/state_management/event_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:http/http.dart' as http;
import 'package:intl/date_symbol_data_local.dart';
import 'package:provider/provider.dart';

import 'core/theme/theme_provider.dart';
import 'data/providers/friends_provider.dart';
import 'domain/entities/user.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialisation du format de date en français
  await initializeDateFormatting('fr_FR', null);

  // Initialisation des services nécessaires
  final eventRemoteDataSource = EventRemoteDataSource(http.Client());
  final SecureStorage secureStorage = SecureStorage();
  final PreferencesHelper preferencesHelper = PreferencesHelper();
  final http.Client httpClient = http.Client();

  // Récupération des informations stockées avec logs détaillés
  String? userId = await secureStorage.getUserId();
  String? userFirstName = await preferencesHelper.getUseFirstrName();
  String? userLastName = await preferencesHelper.getUserLastName();

  // Log de la récupération des informations
  print("[LOG] Récupération des informations utilisateur : userId = $userId, userFirstName = $userFirstName, userLastName = $userLastName");

  // Gestion des valeurs par défaut si les informations ne sont pas trouvées
  userId ??= 'default_user_id';
  userFirstName ??= 'Default';
  userLastName ??= 'User';

  // Log des valeurs par défaut appliquées
  print("[LOG] Valeurs par défaut appliquées : userId = $userId, userFirstName = $userFirstName, userLastName = $userLastName");

  // Création de l'objet User
  final User user = User(
    userId: userId,
    userLastName: userLastName,
    userFirstName: userFirstName,
    email: 'user@example.com',
    motDePasse: 'motDePasseHashé',
    profileImageUrl: 'lib/assets/images/profile_picture.png',
    eventsCount: 0,
    friendsCount: 0,
    postsCount: 0,
    visitedPlacesCount: 0,
  );

  runApp(MyApp(
    eventRemoteDataSource: eventRemoteDataSource,
    user: user,
    httpClient: httpClient,
  ));
}

class MyApp extends StatelessWidget {
  final EventRemoteDataSource eventRemoteDataSource;
  final User user;
  final http.Client httpClient;

  const MyApp({
    super.key,
    required this.eventRemoteDataSource,
    required this.user,
    required this.httpClient,
  });

  @override
  Widget build(BuildContext context) {
    final friendsRepository = FriendsRepositoryImpl(client: httpClient);

    // Log lors de la construction de l'application
    print("[LOG] Construction de l'application avec user : ${user.toString()}");

    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => UserProvider()..setUser(user),
        ),
        ChangeNotifierProvider(
          create: (_) => FriendsProvider(friendsRepository: friendsRepository),
        ),
        ChangeNotifierProvider(
          create: (_) => ThemeProvider(),
        ),
        BlocProvider(
          create: (context) => EventBloc(remoteDataSource: eventRemoteDataSource),
        ),
      ],
      child: Consumer<ThemeProvider>(
        builder: (context, themeProvider, _) {
          return MaterialApp(
            title: 'AfterWork',
            theme: themeProvider.currentTheme,
            onGenerateRoute: AppRouter(
              eventRemoteDataSource: eventRemoteDataSource,
              userId: user.userId,
              userFirstName: user.userFirstName,
              userLastName: user.userLastName,
            ).generateRoute,
            initialRoute: '/',
          );
        },
      ),
    );
  }
}

