import 'dart:async';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/core/network/dio_http_service.dart';
import 'package:mypoint_flutter_app/shared/preferences/data_preference.dart';
import 'package:mypoint_flutter_app/shared/widgets/loading/app_loading.dart';
import 'package:mypoint_flutter_app/app/config/env_loader.dart';
import 'package:mypoint_flutter_app/core/services/web/web_helper.dart';
import '../features/home/header_home_viewmodel.dart';
import '../core/firebase/push_notification.dart';
import '../core/firebase/push_setup.dart';
import '../core/services/deep_link_service.dart';

/// Main app initialization and setup
class AppInitializer {
  static const Duration _asyncInitTimeout = Duration(seconds: 8);

  /// Initialize all core app features
  static Future<void> initialize() async {
    debugPrint('🚀 Initializing app...');
    await loadEnv();
    await DataPreference.instance.init();
    DioHttpService();
    Get.put(HeaderThemeController(), permanent: true);
    await _runStep(
      label: 'Firebase',
      action: _initializeFirebase,
      timeout: _asyncInitTimeout,
    );
    await _runStep(
      label: 'Web features',
      action: _initializeWebFeatures,
      timeout: _asyncInitTimeout,
    );
    await _runStep(
      label: 'DeepLinkService',
      action: () => DeepLinkService().initialize(),
      timeout: _asyncInitTimeout,
    );
    debugPrint('✅ App initialization completed');
  }

  /// Initialize web-specific features
  static Future<void> _initializeWebFeatures() async {
    if (kIsWeb) {
      debugPrint('🌐 Initializing web-specific features...');
      try {
        await webInitializeXAppSDK();
        await _configureWebSdkHeader();
        debugPrint('✅ Web features initialized successfully');
      } catch (e) {
        debugPrint('❌ Error initializing web features: $e');
      }
    } else {
      debugPrint('📱 Skipping web features initialization for mobile');
    }
  }

  /// Initialize Firebase and FCM (mobile only)
  static Future<void> _initializeFirebase() async {
    if (kIsWeb) return;
    await initFirebaseAndFcm();
  }

  static Future<void> _configureWebSdkHeader() async {
    try {
      final response = await webConfigUIApp({
        'mode': 'mini',
        'iconNavigationColor': '#000000',
        'navigationColor': '#FFFFFF',
        // 'iconNavigationPosision': 'right',
        'headerTitle': 'MyPoint',
        // 'headerSubTitle': 'Tích điểm - đổi quà nhanh chóng',
        'headerColor': '#E71D28',
        // 'headerTextColor': '#000000',
        // 'headerIcon': 'https://cdn.mypoint.vn/app_assets/mypoint_icon.png',
      });
      if (response != null) {
        debugPrint('🧭 x-app-sdk header configured: $response');
      }
    } catch (error) {
      debugPrint('❌ Failed to configure x-app-sdk header: $error');
    }
  }

  static Future<void> _runStep({
    required String label,
    required Future<void> Function() action,
    Duration? timeout,
  }) async {
    try {
      if (timeout != null) {
        await action().timeout(timeout);
      } else {
        await action();
      }
    } on TimeoutException {
      debugPrint('⏱️ $label initialization timed out after ${timeout?.inSeconds}s, continuing without it');
    } catch (e, s) {
      debugPrint('❌ $label initialization failed: $e');
      debugPrintStack(stackTrace: s);
    }
  }

  /// Setup post-initialization callbacks
  static void setupPostInitCallbacks() {
    try {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        AppLoading().attach();
      });
      _handleInitialNotificationLaunch();
      handleLocalNotificationLaunchIfAny();
    } catch (e) {
      debugPrint('Error in setupPostInitCallbacks: $e');
    }
  }

  /// Handle initial notification launch (mobile only)
  static Future<void> _handleInitialNotificationLaunch() async {
    if (kIsWeb) return; // Skip for web
    final initial = await FirebaseMessaging.instance.getInitialMessage();
    if (initial == null) return;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Future.delayed(const Duration(seconds: 1), () {
        NotificationRouter.handleRemoteMessage(initial);
      });
    });
  }
}
