// ignore_for_file: constant_identifier_names

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

import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hub/features/notification/index.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/internationalization.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/utils/test_util.dart';
import 'package:responsive_framework/responsive_framework.dart';

import 'initialization.dart';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  await initializeApp();
  runApp(const ProviderScope(child: App()));
  FirebaseMessaging.onBackgroundMessage(_backgroundHandlerMessage);
}

Future<void> _foregroundHandlerMessage(RemoteMessage message) async {
  if (message.data['click_action'] == 'enroll_cond') {
    await StorageHelper().set(SecureStorageKey.haveLocal.value, true);
    StorageHelper().context?.go('/homePage');
  }

  if (!Platform.isIOS) {
    NotificationService.show(
        title: message.notification!.title!,
        body: message.notification!.body!,
        payload: Map<String, String>.from(message.data));
  }
}

Future<void> _backgroundHandlerMessage(RemoteMessage message) async {
  if (message.data['click_action'] == 'enroll_cond') {
    await StorageHelper().set(SecureStorageKey.haveLocal.value, true);
    StorageHelper().context?.go('/homePage');
  }
}

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

  @override
  State<App> createState() => _AppState();

  static _AppState of(BuildContext context) =>
      context.findAncestorStateOfType<_AppState>()!;
}

class _AppState extends State<App> {
  Locale? _locale = FFLocalizations.getStoredLocale();
  ThemeMode _themeMode = FlutterFlowTheme.themeMode;
  late AppStateNotifier _appStateNotifier;
  late GoRouter _router;
  bool displaySplashImage = true;

  final ThemeData _darkTheme = ThemeData(
    brightness: Brightness.dark,
    scrollbarTheme: ScrollbarThemeData(
      thumbVisibility: WidgetStateProperty.all(false),
      interactive: false,
      thumbColor: WidgetStateProperty.resolveWith((states) {
        if (states.contains(WidgetState.dragged)) {
          return const Color(0xff1aab5f);
        }
        if (states.contains(WidgetState.hovered)) {
          return const Color(0xff1aab5f);
        }
        return const Color(0xff1aab5f);
      }),
    ),
  );
  final ThemeData _theme = ThemeData(
    brightness: Brightness.light,
    scrollbarTheme: ScrollbarThemeData(
      thumbVisibility: WidgetStateProperty.all(false),
      interactive: false,
      thumbColor: WidgetStateProperty.resolveWith((states) {
        if (states.contains(WidgetState.dragged)) {
          return const Color(0xff1aab5f);
        }
        if (states.contains(WidgetState.hovered)) {
          return const Color(0xff1aab5f);
        }
        return const Color(0xff1aab5f);
      }),
    ),
  );
  final Iterable<LocalizationsDelegate<dynamic>>? localizationsDelegates =
      const [
    FFLocalizationsDelegate(),
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ];
  final Iterable<Locale> supportedLocales = const [
    Locale('pt'),
    Locale('en'),
  ];
  Widget Function(BuildContext, Widget?)? builder = (context, widget) {
    const String HD4K = '4K';
    const String ULTRAWIDE = 'ULTRAWIDE';

    final breakpoints = [
      const Breakpoint(start: 0, end: 450, name: MOBILE),
      const Breakpoint(start: 451, end: 800, name: TABLET),
      const Breakpoint(start: 801, end: 1920, name: DESKTOP),
      const Breakpoint(start: 1921, end: 2560, name: HD4K),
      const Breakpoint(start: 2561, end: double.infinity, name: ULTRAWIDE),
    ];

    return ResponsiveBreakpoints.builder(
      child: BouncingScrollWrapper.builder(context, widget!),
      breakpoints: breakpoints,
    );
  };

  void _setupFirebaseMessaging() async {
    FirebaseMessaging messaging = FirebaseMessaging.instance;
    RemoteMessage? initialMessage = await messaging.getInitialMessage();
    if (initialMessage != null) {
      log('initialMessage');
      _backgroundHandlerMessage(initialMessage);
    }

    FirebaseMessaging.onMessage.listen(_foregroundHandlerMessage);
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
      if (message.data['click_action'] == 'enroll_cond') {
        await StorageHelper().set(SecureStorageKey.haveLocal.value, true);
        log('onMessageOpenedApp');
      } else {
        onMessageReceived(message.data, message.notification!.body,
            message.data['click_action']);
      }
    });
    FirebaseMessaging.instance.getInitialMessage().then((message) async {
      if (message != null) {
        if (message.data['click_action'] == 'enroll_cond') {
          await StorageHelper().set(SecureStorageKey.haveLocal.value, true);
          log('getInitialMessage');
        }
      }
    });
  }

  void setLocale(String language) {
    setState(() => _locale = createLocale(language));
    FFLocalizations.storeLocale(language);
  }

  void setThemeMode(ThemeMode mode) {
    setState(() {
      _themeMode = mode;
      FlutterFlowTheme.saveThemeMode(mode);
    });
  }

  @override
  void initState() {
    super.initState();

    FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
    _appStateNotifier = AppStateNotifier.instance;
    _router = createRouter(_appStateNotifier);
    Future.delayed(
      const Duration(milliseconds: 1000),
      () => mounted
          ? setState(() => _appStateNotifier.stopShowingSplashImage())
          : null,
    );

    _setupFirebaseMessaging();
    // if (TestUtil.isInTest) //
    DeepLinkService().ensureInitialization();
  }

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      key: navigatorKey,
      title: 'FRE ACCESS HUB',
      builder: builder,
      localizationsDelegates: localizationsDelegates,
      locale: _locale,
      supportedLocales: supportedLocales,
      theme: _theme,
      darkTheme: _darkTheme,
      themeMode: _themeMode,
      routerConfig: _router,
    );
  }
}
