import 'package:flutter/foundation.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:geosector_app/core/constants/app_keys.dart';
import 'package:geosector_app/core/data/models/amicale_model.dart';
import 'package:geosector_app/core/services/current_user_service.dart';

class CurrentAmicaleService extends ChangeNotifier {
  static CurrentAmicaleService? _instance;
  static CurrentAmicaleService get instance =>
      _instance ??= CurrentAmicaleService._internal();
  CurrentAmicaleService._internal();

  AmicaleModel? _currentAmicale;

  // === GETTERS ===
  AmicaleModel? get currentAmicale => _currentAmicale;
  bool get hasAmicale => _currentAmicale != null;
  int? get amicaleId => _currentAmicale?.id;
  String? get amicaleName => _currentAmicale?.name;
  String? get amicaleEmail => _currentAmicale?.email;
  String? get amicalePhone => _currentAmicale?.phone;
  String? get amicaleMobile => _currentAmicale?.mobile;
  String? get amicaleAddress => _currentAmicale != null
      ? '${_currentAmicale!.adresse1} ${_currentAmicale!.adresse2}'.trim()
      : null;
  String? get amicaleFullAddress => _currentAmicale != null
      ? '${amicaleAddress ?? ''} ${_currentAmicale!.codePostal} ${_currentAmicale!.ville}'
          .trim()
      : null;
  bool get amicaleIsActive => _currentAmicale?.chkActive ?? false;
  bool get isClient => _currentAmicale?.fkType == 1;

  // Géolocalisation
  bool get hasGpsCoordinates =>
      _currentAmicale?.gpsLat.isNotEmpty == true &&
      _currentAmicale?.gpsLng.isNotEmpty == true;

  double? get latitude =>
      hasGpsCoordinates ? double.tryParse(_currentAmicale!.gpsLat) : null;

  double? get longitude =>
      hasGpsCoordinates ? double.tryParse(_currentAmicale!.gpsLng) : null;

  // === SETTERS ===
  Future<void> setAmicale(AmicaleModel? amicale) async {
    _currentAmicale = amicale;
    await _saveToHive();
    notifyListeners();
    debugPrint('🏢 Amicale définie: ${amicale?.name ?? 'null'}');
  }

  Future<void> updateAmicale(AmicaleModel updatedAmicale) async {
    _currentAmicale = updatedAmicale;
    await _saveToHive();
    notifyListeners();
    debugPrint('🏢 Amicale mise à jour: ${updatedAmicale.name}');
  }

  Future<void> clearAmicale() async {
    final amicaleName = _currentAmicale?.name;
    _currentAmicale = null;
    await _clearFromHive();
    notifyListeners();
    debugPrint('🏢 Amicale effacée: $amicaleName');
  }

  // === AUTO-LOAD BASÉ SUR L'UTILISATEUR ===
  Future<void> loadUserAmicale() async {
    final user = CurrentUserService.instance.currentUser;
    if (user?.fkEntite != null) {
      await loadAmicaleById(user!.fkEntite!);
    } else {
      await clearAmicale();
    }
  }

  Future<void> loadAmicaleById(int amicaleId) async {
    try {
      final box = Hive.box<AmicaleModel>(AppKeys.amicaleBoxName);
      final amicale = box.get('current_amicale');

      if (amicale?.id == amicaleId) {
        _currentAmicale = amicale;
        debugPrint('📥 Amicale chargée depuis Hive: ${amicale?.name}');
      } else {
        // Si l'amicale n'est pas la bonne, la chercher ou l'effacer
        _currentAmicale = null;
        debugPrint('⚠️ Amicale $amicaleId non trouvée dans Hive');
      }
      notifyListeners();
    } catch (e) {
      debugPrint('❌ Erreur chargement amicale depuis Hive: $e');
      _currentAmicale = null;
    }
  }

  // === PERSISTENCE HIVE ===
  Future<void> _saveToHive() async {
    try {
      if (_currentAmicale != null) {
        // Sauvegarder l'amicale dans sa box
        final box = Hive.box<AmicaleModel>(AppKeys.amicaleBoxName);
        await box.put(_currentAmicale!.id, _currentAmicale!);

        // Sauvegarder l'ID dans settings pour la restauration de session
        if (Hive.isBoxOpen(AppKeys.settingsBoxName)) {
          final settingsBox = Hive.box(AppKeys.settingsBoxName);
          await settingsBox.put('current_amicale_id', _currentAmicale!.id);
          debugPrint('💾 ID amicale ${_currentAmicale!.id} sauvegardé dans settings');
        }

        debugPrint('💾 Amicale sauvegardée dans Hive');
      }
    } catch (e) {
      debugPrint('❌ Erreur sauvegarde amicale Hive: $e');
    }
  }

  Future<void> _clearFromHive() async {
    try {
      // Effacer l'amicale de la box
      if (_currentAmicale != null) {
        final box = Hive.box<AmicaleModel>(AppKeys.amicaleBoxName);
        await box.delete(_currentAmicale!.id);
      }

      // Effacer l'ID des settings
      if (Hive.isBoxOpen(AppKeys.settingsBoxName)) {
        final settingsBox = Hive.box(AppKeys.settingsBoxName);
        await settingsBox.delete('current_amicale_id');
        debugPrint('🗑️ ID amicale effacé des settings');
      }

      debugPrint('🗑️ Amicale effacée de Hive');
    } catch (e) {
      debugPrint('❌ Erreur effacement amicale Hive: $e');
    }
  }

  Future<void> loadFromHive() async {
    try {
      final box = Hive.box<AmicaleModel>(AppKeys.amicaleBoxName);
      _currentAmicale = box.get('current_amicale');

      if (_currentAmicale != null) {
        debugPrint('📥 Amicale chargée depuis Hive: ${_currentAmicale!.name}');
      } else {
        debugPrint('ℹ️ Aucune amicale trouvée dans Hive');
      }

      notifyListeners();
    } catch (e) {
      debugPrint('❌ Erreur chargement amicale depuis Hive: $e');
      _currentAmicale = null;
    }
  }

  // === RESET POUR TESTS ===
  static void reset() {
    _instance?._currentAmicale = null;
    _instance = null;
  }
}
