import 'dart:convert';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:on_field_work/controller/project_controller.dart';
import 'package:on_field_work/helpers/services/auth_service.dart';
import 'package:on_field_work/helpers/services/localizations/language.dart';
import 'package:on_field_work/helpers/theme/theme_customizer.dart';
import 'package:on_field_work/model/employees/employee_info.dart';
import 'package:on_field_work/model/user_permission.dart';
import 'package:on_field_work/model/dynamicMenu/dynamic_menu_model.dart';

class LocalStorage {
  static const String _loggedInUserKey = "user";
  static const String _themeCustomizerKey = "theme_customizer";
  static const String _languageKey = "lang_code";
  static const String _jwtTokenKey = "jwt_token";
  static const String _refreshTokenKey = "refresh_token";
  static const String _userPermissionsKey = "user_permissions";
  static const String _employeeInfoKey = "employee_info";
  static const String _mpinTokenKey = "mpinToken";
  static const String _isMpinKey = "isMpin";
  static const String _fcmTokenKey = "fcm_token";
  static const String _menuStorageKey = "dynamic_menus";
// In LocalStorage
  static const String _recentTenantKey = "recent_tenant_id";

  static Future<bool> setRecentTenantId(String tenantId) =>
      preferences.setString(_recentTenantKey, tenantId);

  static String? getRecentTenantId() =>
      _initialized ? preferences.getString(_recentTenantKey) : null;

  static Future<bool> removeRecentTenantId() =>
      preferences.remove(_recentTenantKey);

  static SharedPreferences? _preferencesInstance;
  static bool _initialized = false;

  static bool get isInitialized => _initialized;

  static SharedPreferences get preferences {
    if (_preferencesInstance == null) {
      throw ("Call LocalStorage.init() before using it");
    }
    return _preferencesInstance!;
  }

  /// Initialization (idempotent)
  static Future<void> init() async {
    if (_initialized) return;
    _preferencesInstance = await SharedPreferences.getInstance();
    await _initData();
    _initialized = true;
  }

  static Future<void> _initData() async {
    AuthService.isLoggedIn = preferences.getBool(_loggedInUserKey) ?? false;
    ThemeCustomizer.fromJSON(preferences.getString(_themeCustomizerKey));
  }

  // ================== Sidebar Menu ==================
  static Future<bool> setMenus(List<MenuItem> menus) async {
    try {
      final jsonList = menus.map((e) => e.toJson()).toList();
      return preferences.setString(_menuStorageKey, jsonEncode(jsonList));
    } catch (e) {
      print("Error saving menus: $e");
      return false;
    }
  }

  static List<MenuItem> getMenus() {
    if (!_initialized) return [];
    final storedJson = preferences.getString(_menuStorageKey);
    if (storedJson == null) return [];
    try {
      return (jsonDecode(storedJson) as List)
          .map((e) => MenuItem.fromJson(e as Map<String, dynamic>))
          .toList();
    } catch (e) {
      print("Error loading menus: $e");
      return [];
    }
  }

  static Future<bool> removeMenus() => preferences.remove(_menuStorageKey);

  // ================== User Permissions ==================
  static Future<bool> setUserPermissions(
      List<UserPermission> permissions) async {
    final jsonList = permissions.map((e) => e.toJson()).toList();
    return preferences.setString(_userPermissionsKey, jsonEncode(jsonList));
  }

  static List<UserPermission> getUserPermissions() {
    if (!_initialized) return [];
    final storedJson = preferences.getString(_userPermissionsKey);
    if (storedJson == null) return [];
    return (jsonDecode(storedJson) as List)
        .map((e) => UserPermission.fromJson(e as Map<String, dynamic>))
        .toList();
  }

  static Future<bool> removeUserPermissions() =>
      preferences.remove(_userPermissionsKey);

  // ================== Employee Info ==================
  static Future<bool> setEmployeeInfo(EmployeeInfo employeeInfo) => preferences
      .setString(_employeeInfoKey, jsonEncode(employeeInfo.toJson()));

  static EmployeeInfo? getEmployeeInfo() {
    if (!_initialized) return null;
    final storedJson = preferences.getString(_employeeInfoKey);
    return storedJson == null
        ? null
        : EmployeeInfo.fromJson(jsonDecode(storedJson));
  }

  static Future<bool> removeEmployeeInfo() =>
      preferences.remove(_employeeInfoKey);

  // ================== Login / Logout ==================
  static Future<bool> setLoggedInUser(bool loggedIn) =>
      preferences.setBool(_loggedInUserKey, loggedIn);

  static Future<bool> removeLoggedInUser() =>
      preferences.remove(_loggedInUserKey);

  static Future<void> logout() async {
    try {
      final refreshToken = getRefreshToken();
      final fcmToken = getFcmToken();

      if (refreshToken != null && fcmToken != null) {
        await AuthService.logoutApi(refreshToken, fcmToken);
      }
    } catch (e) {
      print("Logout API error: $e");
    }

    await removeLoggedInUser();
    await removeToken(_jwtTokenKey);
    await removeToken(_refreshTokenKey);
    await removeUserPermissions();
    await removeEmployeeInfo();
    await removeMpinToken();
    await removeIsMpin();
    await removeMenus();
    await removeRecentTenantId(); 
    await preferences.remove("mpin_verified");
    await preferences.remove(_languageKey);
    await preferences.remove(_themeCustomizerKey);
    await preferences.remove('selectedProjectId');

    if (Get.isRegistered<ProjectController>()) {
      Get.find<ProjectController>().clearProjects();
    }

    Get.offAllNamed('/auth/login-option');
  }

  // ================== Theme & Language ==================
  static Future<bool> setCustomizer(ThemeCustomizer themeCustomizer) =>
      preferences.setString(_themeCustomizerKey, themeCustomizer.toJSON());

  static Future<bool> setLanguage(Language language) =>
      preferences.setString(_languageKey, language.locale.languageCode);

  static String? getLanguage() =>
      _initialized ? preferences.getString(_languageKey) : null;

  // ================== Tokens ==================
  static Future<bool> setToken(String key, String token) =>
      preferences.setString(key, token);

  static String? getToken(String key) =>
      _initialized ? preferences.getString(key) : null;

  static Future<bool> removeToken(String key) => preferences.remove(key);

  static Future<bool> setJwtToken(String jwtToken) =>
      setToken(_jwtTokenKey, jwtToken);

  static Future<bool> setRefreshToken(String refreshToken) =>
      setToken(_refreshTokenKey, refreshToken);

  static String? getJwtToken() => getToken(_jwtTokenKey);

  static String? getRefreshToken() => getToken(_refreshTokenKey);

  // ================== FCM Token ==================
  static Future<void> setFcmToken(String token) =>
      preferences.setString(_fcmTokenKey, token);

  static String? getFcmToken() =>
      _initialized ? preferences.getString(_fcmTokenKey) : null;

  // ================== MPIN ==================
  static Future<bool> setMpinToken(String token) =>
      preferences.setString(_mpinTokenKey, token);

  static String? getMpinToken() =>
      _initialized ? preferences.getString(_mpinTokenKey) : null;

  static Future<bool> removeMpinToken() => preferences.remove(_mpinTokenKey);

  static Future<bool> setIsMpin(bool value) =>
      preferences.setBool(_isMpinKey, value);

  static bool getIsMpin() =>
      _initialized ? preferences.getBool(_isMpinKey) ?? false : false;

  static Future<bool> removeIsMpin() => preferences.remove(_isMpinKey);

  // ================== Generic Set/Get ==================
  static Future<bool> setBool(String key, bool value) =>
      preferences.setBool(key, value);

  static bool? getBool(String key) =>
      _initialized ? preferences.getBool(key) : null;

  static String? getString(String key) =>
      _initialized ? preferences.getString(key) : null;

  static Future<bool> saveString(String key, String value) =>
      preferences.setString(key, value);
}
