import 'package:flutter/material.dart';
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_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';

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();  // Nouvelle instance http.Client

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

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

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

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

  runApp(MyApp(
    eventRemoteDataSource: eventRemoteDataSource,
    userId: userId,
    userName: userName,
    userLastName: userLastName,
    httpClient: httpClient,  // Passe l'instance client ici
  ));
}

class MyApp extends StatelessWidget {
  final EventRemoteDataSource eventRemoteDataSource;
  final String userId;
  final String userName;
  final String userLastName;
  final http.Client httpClient;  // Ajout de ce paramètre

  const MyApp({
    super.key,
    required this.eventRemoteDataSource,
    required this.userId,
    required this.userName,
    required this.userLastName,
    required this.httpClient,  // Spécifier l'argument
  });

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

    // Log lors de la construction de l'application
    print("[LOG] Construction de l'application avec userId : $userId, userName : $userName, userLastName : $userLastName");

    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => UserProvider()..setUser(userId, userName, userLastName),
        ),
        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: userId,
              userName: userName,
              userLastName: userLastName,
            ).generateRoute,
            initialRoute: '/',
          );
        },
      ),
    );
  }
}
