// main.dart
import 'dart:ui';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:provider/single_child_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tm_app/core/config/dependencies.dart';
import 'package:tm_app/core/config/web_url_strategy.dart';
import 'package:tm_app/core/services/cache_init.dart';
import 'package:tm_app/core/services/firebase_service.dart';
import 'package:tm_app/core/theme/theme_provider.dart';
import 'package:tm_app/core/utils/app_toast.dart';
import 'package:toastification/toastification.dart';

import 'core/routes/app_routes.dart';
import 'core/theme/colors.dart';
import 'core/utils/logger.dart';

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

  // Initialize SVG cache
  await CacheInit.init();

  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

  // Initialize the logger
  appLogger.init();

  // Log app start
  appLogger.info('🚀 Starting TM App...');
  // appLogger.logNavigation('Home', 'Login');
  final prefs = await SharedPreferences.getInstance();

  List<SingleChildWidget> providers = [
    Provider(create: (context) => prefs),
    ...providersRemote,
  ];
  // Configure web URL strategy if running on web
  configureWebUrlStrategy();

  await FirebaseService().initializeApp();

  runApp(MultiProvider(providers: providers, child: const MyApp()));
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<void> setupInteractedMessage() async {
    final initialMessage = await FirebaseMessaging.instance.getInitialMessage();

    if (initialMessage != null) {
      _handleMessage(initialMessage);
    }

    if (kIsWeb) {
      FirebaseMessaging.onMessage.listen((event) {
        final overlayCtx = rootNavigatorKey.currentContext;
        if (overlayCtx != null) {
          if (overlayCtx.mounted) {
            AppToast.notification(
              overlayCtx,
              event.notification?.title ?? 'New Notification',
              event.notification?.body ?? 'New Notification',
            );
          }
        }
      });
    }

    FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
  }

  void _handleMessage(RemoteMessage message) {
    appRouter.go(
      const SplashScreenRoute(navigateToNotification: true).location,
    );
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setupInteractedMessage();
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // Set the context for ThemeProvider to enable forced rebuilds
    ThemeProvider.setContext(context);
  }

  @override
  Widget build(BuildContext context) {
    // Listen to theme changes
    final themeProvider = context.watch<ThemeProvider>();

    return ToastificationWrapper(
      child: MaterialApp.router(
        title: 'OppLens',
        debugShowCheckedModeBanner: false,
        scrollBehavior: const MaterialScrollBehavior().copyWith(
          dragDevices: {
            PointerDeviceKind.mouse,
            PointerDeviceKind.touch,
            PointerDeviceKind.stylus,
            PointerDeviceKind.unknown,
          },
        ),
        theme: ThemeData(
          pageTransitionsTheme: PageTransitionsTheme(
            builders: {
              for (final platform in TargetPlatform.values)
                platform:
                    kIsWeb
                        ? const FadeUpwardsPageTransitionsBuilder()
                        : const CupertinoPageTransitionsBuilder(),
            },
          ),
          brightness:
              themeProvider.isDarkMode ? Brightness.dark : Brightness.light,
          primaryColor: AppColors.primaryColor,
          scaffoldBackgroundColor: AppColors.backgroundColor,
          colorScheme: ColorScheme.fromSeed(
            seedColor: AppColors.primaryColor,
            brightness:
                themeProvider.isDarkMode ? Brightness.dark : Brightness.light,
          ),
        ),
        routerConfig: appRouter,
      ),
    );
  }
}
