import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/dio_http_service.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import 'package:mypoint_flutter_app/preference/point/point_manager.dart';
import 'package:mypoint_flutter_app/screen/home/header_home_viewmodel.dart';
import 'package:mypoint_flutter_app/firebase/push_notification.dart';
import 'package:mypoint_flutter_app/firebase/push_setup.dart';
import 'package:mypoint_flutter_app/base/app_loading.dart';
import 'package:mypoint_flutter_app/env_loader.dart';
import 'package:mypoint_flutter_app/web/web_app_initializer.dart';
import 'package:mypoint_flutter_app/core/deep_link_service.dart';

/// Main app initialization and setup
class AppInitializer {
  /// Initialize all core app features
  static Future<void> initialize() async {
    print('🚀 Initializing app...');
    // Load environment configuration
    await loadEnv();
    // Initialize data preferences
    await DataPreference.instance.init();
    // Initialize HTTP service
    DioHttpService();
    // Initialize GetX controllers
    Get.put(HeaderThemeController(), permanent: true);
    // Initialize Firebase (mobile only)
    await _initializeFirebase();
    // Fetch user point if logged in
    await _fetchUserPointIfLoggedIn();
    // Initialize web-specific features
    await WebAppInitializer.initialize();
    // Initialize deep links
    await DeepLinkService().initialize();
    print('✅ App initialization completed');
  }

  /// Initialize Firebase and FCM (mobile only)
  static Future<void> _initializeFirebase() async {
    if (!kIsWeb) {
      print('📱 Initializing Firebase for mobile...');
      await initFirebaseAndFcm();
    } else {
      print('🌐 Skipping Firebase initialization for web');
    }
  }

  /// Fetch user point if already logged in
  static Future<void> _fetchUserPointIfLoggedIn() async {
    if (DataPreference.instance.logged) {
      print('💰 Fetching user point...');
      await UserPointManager().fetchUserPoint();
    } else {
      print('👤 User not logged in, skipping point fetch');
    }
  }

  /// Setup post-initialization callbacks
  static void setupPostInitCallbacks() {
    try {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        AppLoading().attach();
      });
      // Handle launch from notification when app was killed
      _handleInitialNotificationLaunch();
      // Handle launch from local notification tap when app was killed
      handleLocalNotificationLaunchIfAny();
    } catch (e) {
      if (kDebugMode) print('Error in setupPostInitCallbacks: $e');
    }
  }

  /// Handle initial notification launch
  static Future<void> _handleInitialNotificationLaunch() async {
    try {
      final initial = await FirebaseMessaging.instance.getInitialMessage();
      print('Checking initial message for app launch from terminated state...$initial');
      if (initial == null) return;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Future.delayed(const Duration(seconds: 1), () {
          NotificationRouter.handleRemoteMessage(initial);
        });
      });
    } catch (_) {}
  }
}