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

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

  List<MaintenanceModel> _maintenances = [];
  bool _isLoading = false;

  List<MaintenanceModel> get maintenances => _maintenances;
  bool get isLoading => _isLoading;

  /// Charger toutes les maintenances via l'API
  Future<void> loadMaintenances({String? equipmentId}) async {
    _isLoading = true;
    notifyListeners();

    try {
      final maintenancesData = await _dataService.getMaintenances(
        equipmentId: equipmentId,
      );

      _maintenances = maintenancesData.map((data) {
        return MaintenanceModel.fromMap(data, data['id'] as String);
      }).toList();

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

  /// Recharger les maintenances
  Future<void> refresh({String? equipmentId}) async {
    await loadMaintenances(equipmentId: equipmentId);
  }

  /// Obtenir les maintenances pour un équipement spécifique
  List<MaintenanceModel> getForEquipment(String equipmentId) {
    return _maintenances.where((m) =>
      m.equipmentIds.contains(equipmentId)
    ).toList();
  }
}

