import 'dart:async';
import 'dart:developer';
import 'dart:io';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jiffy/jiffy.dart';
import 'package:loader_overlay/loader_overlay.dart';
import 'package:provider/provider.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'api/mhsl/breaker/getBreakers/getBreakersResponse.dart';
import 'app.dart';
import 'firebase_options.dart';
import 'model/accountData.dart';
import 'model/accountModel.dart';
import 'model/breakers/Breaker.dart';
import 'model/breakers/BreakerProps.dart';
import 'model/chatList/chatListProps.dart';
import 'model/chatList/chatProps.dart';
import 'model/files/filesProps.dart';
import 'model/holidays/holidaysProps.dart';
import 'model/message/messageProps.dart';
import 'model/timetable/timetableProps.dart';
import 'storage/base/settingsProvider.dart';
import 'theming/darkAppTheme.dart';
import 'theming/lightAppTheme.dart';
import 'view/login/login.dart';
import 'widget/placeholderView.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
    log("Firebase token: ${await FirebaseMessaging.instance.getToken() ?? "Error: no Firebase token!"}");
  } catch (e) {
    log('Error initializing Firebase app!');
  }

  var data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
  SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List());

  if(kReleaseMode) {
    ErrorWidget.builder = (error) => PlaceholderView(
        icon: Icons.phonelink_erase_rounded,
        text: error.toStringShort(),
      );
  }

  runApp(
      MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) => BreakerProps()),

          ChangeNotifierProvider(create: (context) => SettingsProvider()),
          ChangeNotifierProvider(create: (context) => AccountModel()),

          ChangeNotifierProvider(create: (context) => TimetableProps()),
          ChangeNotifierProvider(create: (context) => ChatListProps()),
          ChangeNotifierProvider(create: (context) => ChatProps()),
          ChangeNotifierProvider(create: (context) => FilesProps()),

          ChangeNotifierProvider(create: (context) => MessageProps()),
          ChangeNotifierProvider(create: (context) => HolidaysProps()),
        ],
        child: const Main(),
      )
  );
}

class Main extends StatefulWidget {
  const Main({super.key});

  @override
  State<Main> createState() => _MainState();
}

class _MainState extends State<Main> {
  late Timer refetchProps;

  @override
  void initState() {
    Jiffy.setLocale('de');

    AccountData().waitForPopulation().then((value) {
      Provider.of<AccountModel>(context, listen: false)
          .setState(value ? AccountModelState.loggedIn : AccountModelState.loggedOut);
    });

    refetchProps = Timer.periodic(const Duration(seconds: 60), (timer) {
      Provider.of<BreakerProps>(context, listen: false).run();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) => Directionality(
      textDirection: TextDirection.ltr,
      child: Consumer<SettingsProvider>(
        builder: (context, settings, child) {
          var devToolsSettings = settings.val().devToolsSettings;
          return MaterialApp(
            showPerformanceOverlay: devToolsSettings.showPerformanceOverlay,
            checkerboardOffscreenLayers: devToolsSettings.checkerboardOffscreenLayers,
            checkerboardRasterCacheImages: devToolsSettings.checkerboardRasterCacheImages,

            debugShowCheckedModeBanner: false,
            localizationsDelegates: const [
              ...GlobalMaterialLocalizations.delegates,
              GlobalWidgetsLocalizations.delegate,
            ],
            supportedLocales: const [
              Locale('de'),
              Locale('en'),
            ],
            locale: const Locale('de'),

            title: 'Marianum Fulda',
            
            themeMode: settings.val().appTheme,
            theme: LightAppTheme.theme,
            darkTheme: DarkAppTheme.theme,
            home: LoaderOverlay(
              child: Breaker(
                  breaker: BreakerArea.global,
                  child: Consumer<AccountModel>(
                    builder: (context, accountModel, child) {
                      switch(accountModel.state) {
                        case AccountModelState.loggedIn: return const App();
                        case AccountModelState.loggedOut: return const Login();
                        case AccountModelState.undefined: return const PlaceholderView(icon: Icons.timer, text: 'Daten werden geladen');
                      }
                    },
                  )
              ),
            ),
          );
        },
      ),
    );

  @override
  void dispose() {
    refetchProps.cancel();
    super.dispose();
  }
}
