import 'package:flutter/services.dart';
import 'package:url_strategy/url_strategy.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:on_field_work/helpers/services/storage/local_storage.dart';
import 'package:on_field_work/helpers/services/app_logger.dart';
import 'package:on_field_work/helpers/services/auth_service.dart';
import 'package:on_field_work/helpers/services/firebase/firebase_messaging_service.dart';
import 'package:on_field_work/helpers/services/device_info_service.dart';
import 'package:on_field_work/helpers/theme/theme_customizer.dart';
import 'package:on_field_work/helpers/theme/app_theme.dart';

Future<void> initializeApp() async {
  try {
    logSafe("💡 Starting app initialization...");

    await Future.wait([
      _setupUI(),
      _setupFirebase(),
      _setupLocalStorage(),
    ]);

    await _setupDeviceInfo();
    await _handleAuthTokens(); 
    await _setupTheme();
    await _setupFirebaseMessaging();

    _finalizeAppStyle();

    logSafe("✅ App initialization completed successfully.");
  } catch (e, stacktrace) {
    logSafe(
      "⛔ Error during app initialization",
      level: LogLevel.error,
      error: e,
      stackTrace: stacktrace,
    );
    rethrow;
  }
}

Future<void> _handleAuthTokens() async {
  final refreshToken = await LocalStorage.getRefreshToken();
  if (refreshToken?.isNotEmpty ?? false) {
    logSafe("🔁 Refresh token found. Attempting to refresh JWT...");
    final success = await AuthService.refreshToken();
    if (!success) {
      logSafe("⚠️ Refresh token invalid or expired. User must login again.");
    }
  } else {
    logSafe("❌ No refresh token found. Skipping refresh.");
  }
}

Future<void> _setupUI() async {
  setPathUrlStrategy();
  await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
  logSafe("💡 UI setup completed with default system behavior.");
}

Future<void> _setupFirebase() async {
  await Firebase.initializeApp();
  logSafe("💡 Firebase initialized.");
}

Future<void> _setupLocalStorage() async {
  if (!LocalStorage.isInitialized) {
    await LocalStorage.init();
    logSafe("💡 Local storage initialized.");
  } else {
    logSafe("ℹ️ Local storage already initialized, skipping.");
  }
}

Future<void> _setupDeviceInfo() async {
  final deviceInfoService = DeviceInfoService();
  await deviceInfoService.init();
  logSafe("📱 Device Info: ${deviceInfoService.deviceData}");
}

Future<void> _setupTheme() async {
  await ThemeCustomizer.init();
  logSafe("💡 Theme customizer initialized.");
}

Future<void> _setupFirebaseMessaging() async {
  await FirebaseNotificationService().initialize();
  logSafe("💡 Firebase Messaging initialized.");
}

void _finalizeAppStyle() {
  AppStyle.init();
  logSafe("💡 AppStyle initialized.");
}
