import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:youmazgestion/Models/users.dart';
import 'package:youmazgestion/Services/stock_managementDatabase.dart';
import 'package:youmazgestion/Services/PermissionCacheService.dart';

class UserController extends GetxController {
  final _username = ''.obs;
  final _email = ''.obs;
  final _role = ''.obs;
  final _name = ''.obs;
  final _lastname = ''.obs;
  final _password = ''.obs;
  final _userId = 0.obs;
  final _pointDeVenteId = 0.obs;
  final _pointDeVenteDesignation = ''.obs;

  // Cache service
  final PermissionCacheService _cacheService = PermissionCacheService.instance;

  // Getters
  String get username => _username.value;
  String get email => _email.value;
  String get role => _role.value;
  String get name => _name.value;
  String get lastname => _lastname.value;
  String get password => _password.value;
  int get userId => _userId.value;
  int get pointDeVenteId => _pointDeVenteId.value;
  String get pointDeVenteDesignation => _pointDeVenteDesignation.value;

  @override
  void onInit() {
    super.onInit();
    loadUserData();
  }

  /// ✅ SIMPLIFIÉ: Charge les données utilisateur sans cache persistant
  Future<void> loadUserData() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      final storedUsername = prefs.getString('username') ?? '';
      final storedRole = prefs.getString('role') ?? '';
      final storedUserId = prefs.getInt('user_id') ?? 0;
      final storedPointDeVenteId = prefs.getInt('point_de_vente_id') ?? 0;
      final storedPointDeVenteDesignation =
          prefs.getString('point_de_vente_designation') ?? '';

      if (storedUsername.isNotEmpty) {
        try {
          Users user = await AppDatabase.instance.getUser(storedUsername);

          _username.value = user.username;
          _email.value = user.email;
          _name.value = user.name;
          _lastname.value = user.lastName;
          _password.value = user.password;
          _role.value = storedRole;
          _userId.value = storedUserId;
          _pointDeVenteId.value = storedPointDeVenteId;
          _pointDeVenteDesignation.value = storedPointDeVenteDesignation;

          if (_pointDeVenteDesignation.value.isEmpty &&
              _pointDeVenteId.value > 0) {
            await loadPointDeVenteDesignation();
          }

          // ✅ Précharger les permissions en arrière-plan (non bloquant)
          _preloadPermissionsInBackground();
        } catch (dbError) {
          // print("❌ Erreur BDD, utilisation du fallback: $dbError");
          _username.value = storedUsername;
          _email.value = prefs.getString('email') ?? '';
          _role.value = storedRole;
          _name.value = prefs.getString('name') ?? '';
          _lastname.value = prefs.getString('lastname') ?? '';
          _userId.value = storedUserId;
          _pointDeVenteId.value = storedPointDeVenteId;
          _pointDeVenteDesignation.value = storedPointDeVenteDesignation;

          // Précharger quand même
          _preloadPermissionsInBackground();
        }
      }
    } catch (e) {
      // print('❌ Erreur lors du chargement des données utilisateur: $e');
    }
  }

  /// ✅ Précharge les permissions en arrière-plan (non bloquant)
  void _preloadPermissionsInBackground() {
    if (_username.value.isNotEmpty) {
      // Lancer en arrière-plan sans attendre
      Future.microtask(() async {
        try {
          await _cacheService.preloadUserData(_username.value);
        } catch (e) {
          print("⚠️ Erreur préchargement permissions (non critique): $e");
        }
      });
    }
  }

  Future<void> loadPointDeVenteDesignation() async {
    if (_pointDeVenteId.value <= 0) return;

    try {
      final pointDeVente =
          await AppDatabase.instance.getPointDeVenteById(_pointDeVenteId.value);
      if (pointDeVente != null) {
        _pointDeVenteDesignation.value = pointDeVente['nom'] as String;
        await saveUserData();
      }
    } catch (e) {
      print(
          '❌ Erreur lors du chargement de la désignation du point de vente: $e');
    }
  }

  /// ✅ Mise à jour avec préchargement des permissions
  void setUserWithCredentials(Users user, String role, int userId) {
    _username.value = user.username;
    _email.value = user.email;
    _role.value = role;
    _name.value = user.name;
    _lastname.value = user.lastName;
    _password.value = user.password;
    _userId.value = userId;
    _pointDeVenteId.value = user.pointDeVenteId ?? 0;

    // print("✅ Utilisateur mis à jour avec credentials:");
    // print("   Username: ${_username.value}");
    // print("   Role: ${_role.value}");
    // print("   UserID: ${_userId.value}");

    saveUserData();

    // ✅ Précharger immédiatement les permissions après connexion
    _preloadPermissionsInBackground();
  }

  void setUser(Users user) {
    _username.value = user.username;
    _email.value = user.email;
    _role.value = user.role;
    _name.value = user.name;
    _lastname.value = user.lastName;
    _password.value = user.password;

    saveUserData();
    _preloadPermissionsInBackground();
  }

  Future<void> saveUserData() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      await prefs.setString('username', _username.value);
      await prefs.setString('email', _email.value);
      await prefs.setString('role', _role.value);
      await prefs.setString('name', _name.value);
      await prefs.setString('lastname', _lastname.value);
      await prefs.setInt('user_id', _userId.value);
      await prefs.setInt('point_de_vente_id', _pointDeVenteId.value);
      await prefs.setString(
          'point_de_vente_designation', _pointDeVenteDesignation.value);

      // print("✅ Données sauvegardées avec succès");
    } catch (e) {
      print('❌ Erreur lors de la sauvegarde: $e');
    }
  }

  /// ✅ MODIFIÉ: Vider les données ET le cache de session
  Future<void> clearUserData() async {
    try {
      final prefs = await SharedPreferences.getInstance();

      // ✅ IMPORTANT: Vider le cache de session
      _cacheService.clearAllCache();

      // Effacer SharedPreferences
      await prefs.remove('username');
      await prefs.remove('email');
      await prefs.remove('role');
      await prefs.remove('name');
      await prefs.remove('lastname');
      await prefs.remove('user_id');
      await prefs.remove('point_de_vente_id');
      await prefs.remove('point_de_vente_designation');

      // Effacer les observables
      _username.value = '';
      _email.value = '';
      _role.value = '';
      _name.value = '';
      _lastname.value = '';
      _password.value = '';
      _userId.value = 0;
      _pointDeVenteId.value = 0;
      _pointDeVenteDesignation.value = '';

      print("✅ Données utilisateur et cache de session vidés");
    } catch (e) {
      print('❌ Erreur lors de l\'effacement: $e');
    }
  }

  // Getters utilitaires
  bool get isLoggedIn => _username.value.isNotEmpty && _userId.value > 0;
  String get fullName => '${_name.value} ${_lastname.value}'.trim();

  /// ✅ OPTIMISÉ: Vérification des permissions depuis le cache de session
  Future<bool> hasPermission(String permission, String route) async {
    try {
      if (_username.value.isEmpty) {
        print('⚠️ Username vide, rechargement...');
        await loadUserData();
      }

      if (_username.value.isEmpty) {
        print('❌ Utilisateur non connecté');
        return false;
      }

      // Essayer d'abord le cache
      if (_cacheService.isLoaded) {
        return _cacheService.hasPermission(_username.value, permission, route);
      }

      // Si pas encore chargé, charger et essayer de nouveau
      print("🔄 Cache non chargé, chargement des permissions...");
      await _cacheService.loadUserPermissions(_username.value);

      return _cacheService.hasPermission(_username.value, permission, route);
    } catch (e) {
      print('❌ Erreur vérification permission: $e');
      // Fallback vers la méthode originale en cas d'erreur
      try {
        return await AppDatabase.instance
            .hasPermission(_username.value, permission, route);
      } catch (fallbackError) {
        print('❌ Erreur fallback permission: $fallbackError');
        return false;
      }
    }
  }

  /// ✅ Vérification de permissions multiples
  Future<bool> hasAnyPermission(
      List<String> permissionNames, String menuRoute) async {
    for (String permissionName in permissionNames) {
      if (await hasPermission(permissionName, menuRoute)) {
        return true;
      }
    }
    return false;
  }

  /// ✅ Obtenir les menus accessibles depuis le cache
  List<Map<String, dynamic>> getUserMenus() {
    if (_username.value.isEmpty || !_cacheService.isLoaded) return [];
    return _cacheService.getUserMenus(_username.value);
  }

  /// ✅ Vérifier l'accès à un menu depuis le cache
  bool hasMenuAccess(String menuRoute) {
    if (_username.value.isEmpty || !_cacheService.isLoaded) return false;
    return _cacheService.hasMenuAccess(_username.value, menuRoute);
  }

  /// ✅ Forcer le rechargement des permissions (pour les admins après modification)
  Future<void> refreshPermissions() async {
    if (_username.value.isNotEmpty) {
      await _cacheService.refreshUserPermissions(_username.value);
    }
  }

  /// ✅ Vérifier si le cache est prêt
  bool get isCacheReady => _cacheService.isLoaded && _username.value.isNotEmpty;

  /// Debug
  void debugPrintUserState() {
    print("=== ÉTAT UTILISATEUR ===");
    print("Username: ${_username.value}");
    print("Name: ${_name.value}");
    print("Role: ${_role.value}");
    print("UserID: ${_userId.value}");
    print("IsLoggedIn: $isLoggedIn");
    print("Cache Ready: $isCacheReady");
    print("========================");

    // Debug du cache
    _cacheService.debugPrintCache();
  }
}
