import 'package:flutter/foundation.dart';
import 'package:em2rp/models/alert_model.dart';
import 'package:em2rp/services/data_service.dart';
import 'package:em2rp/services/api_service.dart';

class AlertProvider extends ChangeNotifier {
  final DataService _dataService = DataService(FirebaseFunctionsApiService());

  List<AlertModel> _alerts = [];
  bool _isLoading = false;

  List<AlertModel> get alerts => _alerts;
  bool get isLoading => _isLoading;

  /// Nombre d'alertes non lues
  int get unreadCount => _alerts.where((a) => !a.isRead).length;

  /// Charger toutes les alertes via l'API
  Future<void> loadAlerts() async {
    _isLoading = true;
    notifyListeners();

    try {
      final alertsData = await _dataService.getAlerts();

      _alerts = alertsData.map((data) {
        return AlertModel.fromMap(data, data['id'] as String);
      }).toList();

      _isLoading = false;
      notifyListeners();
    } catch (e) {
      print('Error loading alerts: $e');
      _isLoading = false;
      notifyListeners();
      rethrow;
    }
  }

  /// Recharger les alertes
  Future<void> refresh() async {
    await loadAlerts();
  }

  /// Obtenir les alertes non lues
  List<AlertModel> get unreadAlerts {
    return _alerts.where((a) => !a.isRead).toList();
  }

  /// Obtenir les alertes par type
  List<AlertModel> getByType(AlertType type) {
    return _alerts.where((a) => a.type == type).toList();
  }

  /// Obtenir les alertes critiques (stock bas, équipement perdu)
  List<AlertModel> get criticalAlerts {
    return _alerts.where((a) =>
      a.type == AlertType.lowStock || a.type == AlertType.lost
    ).toList();
  }
}

