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/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';

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();

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

  // Gestion des valeurs par défaut si nécessaires
  userId ??= 'default_user_id';
  userName ??= 'Default';
  userLastName ??= 'User';

  runApp(MyApp(
    eventRemoteDataSource: eventRemoteDataSource,
    userId: userId,
    userName: userName,
    userLastName: userLastName,
  ));
}

class MyApp extends StatelessWidget {
  final EventRemoteDataSource eventRemoteDataSource;
  final String userId;
  final String userName;
  final String userLastName;

  const MyApp({
    super.key,
    required this.eventRemoteDataSource,
    required this.userId,
    required this.userName,
    required this.userLastName,
  });

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => UserProvider()..setUser(userId, userName, userLastName),
        ),
        ChangeNotifierProvider(
          create: (_) => ThemeProvider(), // Fournisseur de thème
        ),
        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: '/',
          );
        },
      ),
    );
  }
}
