class ProjectModel {
  final String id;
  final String name;
  final String projectAddress;
  final String contactPerson;
  final DateTime? startDate;
  final DateTime? endDate;
  final int teamSize;
  final double completedWork;
  final double plannedWork;
  final String projectStatusId;
  final String? tenantId;

  ProjectModel({
    required this.id,
    required this.name,
    required this.projectAddress,
    required this.contactPerson,
    this.startDate,
    this.endDate,
    required this.teamSize,
    required this.completedWork,
    required this.plannedWork,
    required this.projectStatusId,
    this.tenantId,
  });

  factory ProjectModel.fromJson(Map<String, dynamic> json) {
    return ProjectModel(
      id: json['id']?.toString() ?? '',
      name: json['name']?.toString() ?? '',
      projectAddress: json['projectAddress']?.toString() ?? '',
      contactPerson: json['contactPerson']?.toString() ?? '',
      startDate: _parseDate(json['startDate']),
      endDate: _parseDate(json['endDate']),
      teamSize: _parseInt(json['teamSize']),
      completedWork: _parseDouble(json['completedWork']),
      plannedWork: _parseDouble(json['plannedWork']),
      projectStatusId: json['projectStatusId']?.toString() ?? '',
      tenantId: json['tenantId']?.toString(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'projectAddress': projectAddress,
      'contactPerson': contactPerson,
      'startDate': startDate?.toIso8601String(),
      'endDate': endDate?.toIso8601String(),
      'teamSize': teamSize,
      'completedWork': completedWork,
      'plannedWork': plannedWork,
      'projectStatusId': projectStatusId,
      'tenantId': tenantId,
    };
  }

  // ---------- Helpers ----------

  static DateTime? _parseDate(dynamic value) {
    if (value == null || value.toString().trim().isEmpty) {
      return null;
    }
    try {
      return DateTime.parse(value.toString());
    } catch (e) {
      print('⚠️ Failed to parse date: $value');
      return null;
    }
  }

  static int _parseInt(dynamic value) {
    if (value == null) return 0;
    if (value is int) return value;
    return int.tryParse(value.toString()) ?? 0;
  }

  static double _parseDouble(dynamic value) {
    if (value == null) return 0.0;
    if (value is num) return value.toDouble();
    return double.tryParse(value.toString()) ?? 0.0;
  }
}
