import 'package:cloud_firestore/cloud_firestore.dart';

enum MaintenanceType {
  preventive,     // Préventive
  corrective,     // Corrective
  inspection      // Inspection
}

String maintenanceTypeToString(MaintenanceType type) {
  switch (type) {
    case MaintenanceType.preventive:
      return 'PREVENTIVE';
    case MaintenanceType.corrective:
      return 'CORRECTIVE';
    case MaintenanceType.inspection:
      return 'INSPECTION';
  }
}

MaintenanceType maintenanceTypeFromString(String? type) {
  switch (type) {
    case 'PREVENTIVE':
      return MaintenanceType.preventive;
    case 'CORRECTIVE':
      return MaintenanceType.corrective;
    case 'INSPECTION':
      return MaintenanceType.inspection;
    default:
      return MaintenanceType.preventive;
  }
}

class MaintenanceModel {
  final String id;                      // ID aléatoire
  final List<String> equipmentIds;      // IDs des équipements concernés (peut être multiple)
  final MaintenanceType type;           // Type de maintenance
  final DateTime scheduledDate;         // Date planifiée
  final DateTime? completedDate;        // Date de réalisation (null si pas encore effectuée)
  final String name;                    // Nom de l'opération
  final String description;             // Description détaillée
  final String? performedBy;            // ID de l'utilisateur qui a effectué la maintenance
  final double? cost;                   // Coût de la maintenance
  final String? notes;                  // Notes additionnelles
  final DateTime createdAt;             // Date de création
  final DateTime updatedAt;             // Date de mise à jour

  MaintenanceModel({
    required this.id,
    required this.equipmentIds,
    required this.type,
    required this.scheduledDate,
    this.completedDate,
    required this.name,
    required this.description,
    this.performedBy,
    this.cost,
    this.notes,
    required this.createdAt,
    required this.updatedAt,
  });

  factory MaintenanceModel.fromMap(Map<String, dynamic> map, String id) {
    // Fonction helper pour convertir de manière sécurisée en double
    double? parseDouble(dynamic value) {
      if (value == null) return null;
      if (value is num) return value.toDouble();
      if (value is String) return double.tryParse(value);
      return null;
    }

    // Fonction helper pour convertir Timestamp ou String ISO ou int epoch en DateTime
    DateTime? parseDate(dynamic value) {
      if (value == null) return null;
      if (value is Timestamp) return value.toDate();
      if (value is String) return DateTime.tryParse(value);
      if (value is int) return DateTime.fromMillisecondsSinceEpoch(value);
      return null;
    }

    // Gestion de la liste des équipements
    final List<String> equipmentIds = [];
    if (map['equipmentIds'] is List) {
      for (final e in map['equipmentIds'] as List) {
        if (e != null) {
          equipmentIds.add(e.toString());
        }
      }
    }

    return MaintenanceModel(
      id: id,
      equipmentIds: equipmentIds,
      type: maintenanceTypeFromString(map['type']?.toString()),
      scheduledDate: parseDate(map['scheduledDate']) ?? DateTime.now(),
      completedDate: parseDate(map['completedDate']),
      name: (map['name'] ?? '').toString(),
      description: (map['description'] ?? '').toString(),
      performedBy: map['performedBy']?.toString(),
      cost: parseDouble(map['cost']),
      notes: map['notes']?.toString(),
      createdAt: parseDate(map['createdAt']) ?? DateTime.now(),
      updatedAt: parseDate(map['updatedAt']) ?? DateTime.now(),
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'equipmentIds': equipmentIds,
      'type': maintenanceTypeToString(type),
      'scheduledDate': Timestamp.fromDate(scheduledDate),
      'completedDate': completedDate != null ? Timestamp.fromDate(completedDate!) : null,
      'name': name,
      'description': description,
      'performedBy': performedBy,
      'cost': cost,
      'notes': notes,
      'createdAt': Timestamp.fromDate(createdAt),
      'updatedAt': Timestamp.fromDate(updatedAt),
    };
  }

  MaintenanceModel copyWith({
    String? id,
    List<String>? equipmentIds,
    MaintenanceType? type,
    DateTime? scheduledDate,
    DateTime? completedDate,
    String? name,
    String? description,
    String? performedBy,
    double? cost,
    String? notes,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return MaintenanceModel(
      id: id ?? this.id,
      equipmentIds: equipmentIds ?? this.equipmentIds,
      type: type ?? this.type,
      scheduledDate: scheduledDate ?? this.scheduledDate,
      completedDate: completedDate ?? this.completedDate,
      name: name ?? this.name,
      description: description ?? this.description,
      performedBy: performedBy ?? this.performedBy,
      cost: cost ?? this.cost,
      notes: notes ?? this.notes,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
    );
  }

  // Helper pour vérifier si la maintenance est complétée
  bool get isCompleted => completedDate != null;

  // Helper pour vérifier si la maintenance est en retard
  bool get isOverdue {
    if (isCompleted) return false;
    return scheduledDate.isBefore(DateTime.now());
  }
}

