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

class AlertProvider extends ChangeNotifier {
  final ApiService _apiService = apiService;

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

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

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

  /// Alertes non lues uniquement
  List<AlertModel> get unreadAlerts => _alerts.where((alert) => !alert.isRead).toList();

  /// Alertes de stock critique
  List<AlertModel> get lowStockAlerts => _alerts.where((alert) => alert.type == AlertType.lowStock).toList();

  /// Alertes de maintenance
  List<AlertModel> get maintenanceAlerts => _alerts.where((alert) => alert.type == AlertType.maintenanceDue).toList();

  /// Alertes de conflit
  List<AlertModel> get conflictAlerts => _alerts.where((alert) => alert.type == AlertType.conflict).toList();

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

    try {
      final result = await _apiService.call('getAlerts', {});
      final alertsData = result['alerts'] as List<dynamic>;

      _alerts = alertsData.map((data) {
        return AlertModel.fromMap(data as Map<String, dynamic>, data['id'] as String);
      }).toList();
    } catch (e) {
      if (kDebugMode) debugPrint('Error loading alerts: $e');
      _alerts = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Marquer une alerte comme lue via Cloud Function
  Future<void> markAsRead(String alertId) async {
    try {
      await _apiService.call('markAlertAsRead', {'alertId': alertId});

      // Mettre à jour localement
      final index = _alerts.indexWhere((a) => a.id == alertId);
      if (index != -1) {
        _alerts[index] = AlertModel(
          id: _alerts[index].id,
          type: _alerts[index].type,
          message: _alerts[index].message,
          equipmentId: _alerts[index].equipmentId,
          isRead: true,
          createdAt: _alerts[index].createdAt,
        );
        notifyListeners();
      }
    } catch (e) {
      if (kDebugMode) debugPrint('Error marking alert as read: $e');
      rethrow;
    }
  }

  /// Supprimer une alerte via Cloud Function
  Future<void> deleteAlert(String alertId) async {
    try {
      await _apiService.call('deleteAlert', {'alertId': alertId});

      // Supprimer localement
      _alerts.removeWhere((a) => a.id == alertId);
      notifyListeners();
    } catch (e) {
      if (kDebugMode) debugPrint('Error deleting alert: $e');
      rethrow;
    }
  }

  /// Marquer toutes les alertes comme lues
  Future<void> markAllAsRead() async {
    try {
      final unreadAlertIds = _alerts.where((a) => !a.isRead).map((a) => a.id).toList();

      for (final alertId in unreadAlertIds) {
        await markAsRead(alertId);
      }
    } catch (e) {
      if (kDebugMode) debugPrint('Error marking all alerts as read: $e');
      rethrow;
    }
  }

  /// Supprimer toutes les alertes lues via Cloud Function
  Future<void> deleteReadAlerts() async {
    try {
      final readAlertIds = _alerts.where((a) => a.isRead).map((a) => a.id).toList();

      for (final alertId in readAlertIds) {
        await deleteAlert(alertId);
      }
    } catch (e) {
      if (kDebugMode) debugPrint('Error deleting read alerts: $e');
      rethrow;
    }
  }
}

