import 'package:device_preview/device_preview.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:media_kit/media_kit.dart';
import 'package:multi_trigger_autocomplete/multi_trigger_autocomplete.dart';
import 'package:provider/provider.dart';

import 'app_theme.dart';
import 'di_initialization.dart';
import 'globals.dart';
import 'routes.dart';
import 'services/auth_service.dart';
import 'services/blocks_manager.dart';
import 'services/connections_manager.dart';
import 'services/direct_message_service.dart';
import 'services/entry_manager_service.dart';
import 'services/follow_requests_manager.dart';
import 'services/gallery_service.dart';
import 'services/hashtag_service.dart';
import 'services/interactions_manager.dart';
import 'services/log_service.dart';
import 'services/notifications_manager.dart';
import 'services/setting_service.dart';
import 'services/status_service.dart';
import 'services/timeline_entry_filter_service.dart';
import 'services/timeline_manager.dart';
import 'utils/active_profile_selector.dart';
import 'utils/app_scrolling_behavior.dart';
import 'utils/old_android_letsencrypte_cert.dart';

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

  final logService = LogService();
  getIt.registerSingleton<LogService>(logService);

  // await dotenv.load(fileName: '.env');
  const enablePreview = false;
  Logger.root.level = Level.OFF;
  Logger.root.onRecord.listen((event) {
    logService.add(event);
  });

  await fixLetsEncryptCertOnOldAndroid();
  await dependencyInjectionInitialization();

  runApp(DevicePreview(
    enabled: !kReleaseMode && enablePreview,
    builder: (context) => const App(),
  ));
}

class App extends StatelessWidget {
  const App({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    final settingsService = getIt<SettingsService>();
    return AnimatedBuilder(
      builder: (context, child) {
        Logger.root.level = settingsService.logLevel;
        print('Log level: ${settingsService.logLevel}');
        return Portal(
          child: MultiProvider(
            providers: [
              ChangeNotifierProvider<LogService>(
                create: (_) => getIt<LogService>(),
                lazy: true,
              ),
              ChangeNotifierProvider<StatusService>(
                create: (_) => getIt<StatusService>(),
                lazy: true,
              ),
              ChangeNotifierProvider<SettingsService>(
                create: (_) => getIt<SettingsService>(),
                lazy: true,
              ),
              ChangeNotifierProvider<AccountsService>(
                create: (_) => getIt<AccountsService>(),
                lazy: true,
              ),
              ChangeNotifierProvider<ActiveProfileSelector<ConnectionsManager>>(
                create: (_) =>
                    getIt<ActiveProfileSelector<ConnectionsManager>>(),
                lazy: true,
              ),
              ChangeNotifierProvider<
                  ActiveProfileSelector<EntryManagerService>>(
                create: (_) =>
                    getIt<ActiveProfileSelector<EntryManagerService>>(),
                lazy: true,
              ),
              ChangeNotifierProvider<ActiveProfileSelector<GalleryService>>(
                create: (_) => getIt<ActiveProfileSelector<GalleryService>>(),
                lazy: true,
              ),
              ChangeNotifierProvider<HashtagService>(
                create: (_) => getIt<HashtagService>(),
                lazy: true,
              ),
              ChangeNotifierProvider<ActiveProfileSelector<TimelineManager>>(
                create: (_) => getIt<ActiveProfileSelector<TimelineManager>>(),
              ),
              ChangeNotifierProvider<
                  ActiveProfileSelector<NotificationsManager>>(
                create: (_) =>
                    getIt<ActiveProfileSelector<NotificationsManager>>(),
              ),
              ChangeNotifierProvider<
                  ActiveProfileSelector<FollowRequestsManager>>(
                create: (_) =>
                    getIt<ActiveProfileSelector<FollowRequestsManager>>(),
              ),
              ChangeNotifierProvider<
                  ActiveProfileSelector<DirectMessageService>>(
                create: (_) =>
                    getIt<ActiveProfileSelector<DirectMessageService>>(),
              ),
              ChangeNotifierProvider<
                  ActiveProfileSelector<InteractionsManager>>(
                create: (_) =>
                    getIt<ActiveProfileSelector<InteractionsManager>>(),
              ),
              ChangeNotifierProvider<ActiveProfileSelector<BlocksManager>>(
                create: (_) => getIt<ActiveProfileSelector<BlocksManager>>(),
              ),
              ChangeNotifierProvider<
                  ActiveProfileSelector<TimelineEntryFilterService>>(
                create: (_) =>
                    getIt<ActiveProfileSelector<TimelineEntryFilterService>>(),
              ),
            ],
            child: MaterialApp.router(
              locale: DevicePreview.locale(context),
              builder: DevicePreview.appBuilder,
              theme: buildTheme(
                brightness: Brightness.light,
                blindnessType: settingsService.colorBlindnessType,
              ),
              darkTheme: buildTheme(
                brightness: Brightness.dark,
                blindnessType: settingsService.colorBlindnessType,
              ),
              themeMode: settingsService.themeMode,
              debugShowCheckedModeBanner: false,
              scrollBehavior: AppScrollingBehavior(),
              routerDelegate: appRouter.routerDelegate,
              routeInformationProvider: appRouter.routeInformationProvider,
              routeInformationParser: appRouter.routeInformationParser,
            ),
          ),
        );
      },
      animation: getIt<SettingsService>(),
    );
  }
}
