import 'package:superport/data/models/model_dto.dart';
import 'package:superport/utils/constants.dart';

// 장비 정보 모델 - Sprint 3: Vendor/Model 체계로 전환
class Equipment {
  final int? id;
  
  // Sprint 3: 새로운 FK 관계 필드들
  final int? modelsId; // models 테이블 FK
  final ModelDto? model; // Model 정보 (Vendor 포함)
  
  // 메인 필드들 - 백엔드 API 호환
  final String equipmentNumber; // 장비 번호 (메인)
  final String? serialNumber;
  final String? barcode;
  final int quantity;
  final DateTime? purchaseDate; // 구매일
  final double? purchasePrice; // 구매 가격
  final DateTime? inDate;
  final String? remark; // 비고
  final String? warrantyLicense; // 워런티 라이센스 명
  DateTime? warrantyStartDate; // 워런티 시작일(수정 가능)
  DateTime? warrantyEndDate; // 워런티 종료일(수정 가능)
  
  // 백엔드 API 연동 필드들
  final int? currentCompanyId; // 현재 배치된 회사 ID  
  final int? warehouseLocationId; // 현재 창고 위치 ID
  final int? currentBranchId; // 현재 배치된 지점 ID (Deprecated)
  final DateTime? lastInspectionDate; // 최근 점검일
  final DateTime? nextInspectionDate; // 다음 점검일
  final String? equipmentStatus; // 장비 상태
  final int? companyId; // 구매처 회사 ID
  
  // Sprint 3: 레거시 호환성 getters (임시 유지 - 점진적 마이그레이션용)
  String get manufacturer => model?.vendor?.name ?? 'N/A';
  String get modelName => model?.name ?? 'N/A';
  String get category1 => 'N/A'; // 더 이상 사용하지 않음
  String get category2 => 'N/A'; // 더 이상 사용하지 않음
  String get category3 => 'N/A'; // 더 이상 사용하지 않음
  
  // 추가 호환성 getters
  ModelDto? get modelDto => model; // stock_in_form 등에서 사용
  
  // 기존 레거시 호환성 필드들 (Deprecated - 하위 호환성 위해 유지)
  @Deprecated('Use equipmentNumber instead')
  String get name => equipmentNumber;
  @Deprecated('Use category1 instead')
  String get category => category1;
  @Deprecated('Use category2 instead')
  String get subCategory => category2;
  @Deprecated('Use category3 instead')
  String get subSubCategory => category3;

  Equipment({
    this.id,
    this.modelsId, // Sprint 3: 새로운 FK
    this.model, // Sprint 3: Model 관계
    required this.equipmentNumber, // 메인 필드
    this.serialNumber,
    this.barcode,
    required this.quantity,
    this.purchaseDate,
    this.purchasePrice,
    this.inDate,
    this.remark,
    this.warrantyLicense,
    this.warrantyStartDate,
    this.warrantyEndDate,
    // 백엔드 API 연동 필드들
    this.currentCompanyId,
    this.warehouseLocationId,
    this.currentBranchId, // Deprecated
    this.lastInspectionDate,
    this.nextInspectionDate,
    this.equipmentStatus,
    this.companyId,
  });
  
  // Sprint 3: Legacy 데이터 변환용 팩토리 (임시 - 마이그레이션 기간 동안만 사용)
  factory Equipment.fromLegacy({
    int? id,
    required String manufacturer,
    required String equipmentNumber,
    required String modelName,
    required String category1,
    required String category2,
    required String category3,
    String? serialNumber,
    String? barcode,
    required int quantity,
    DateTime? purchaseDate,
    double? purchasePrice,
    DateTime? inDate,
    String? remark,
    String? warrantyLicense,
    DateTime? warrantyStartDate,
    DateTime? warrantyEndDate,
    int? currentCompanyId,
    int? warehouseLocationId,
    int? currentBranchId,
    DateTime? lastInspectionDate,
    DateTime? nextInspectionDate,
    String? equipmentStatus,
    int? companyId,
  }) {
    // Legacy 데이터를 새로운 구조로 변환
    // TODO: 실제 Vendor/Model 매핑 로직 추가 필요
    return Equipment(
      id: id,
      modelsId: null, // Legacy 데이터는 models_id 없음
      model: null, // Legacy 데이터는 model 관계 없음
      equipmentNumber: equipmentNumber,
      serialNumber: serialNumber,
      barcode: barcode,
      quantity: quantity,
      purchaseDate: purchaseDate,
      purchasePrice: purchasePrice,
      inDate: inDate,
      remark: remark,
      warrantyLicense: warrantyLicense,
      warrantyStartDate: warrantyStartDate,
      warrantyEndDate: warrantyEndDate,
      currentCompanyId: currentCompanyId,
      warehouseLocationId: warehouseLocationId,
      currentBranchId: currentBranchId,
      lastInspectionDate: lastInspectionDate,
      nextInspectionDate: nextInspectionDate,
      equipmentStatus: equipmentStatus,
      companyId: companyId,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      // Sprint 3: 새로운 FK 관계 필드들
      'models_id': modelsId,
      'model': model?.toJson(),
      // 메인 필드들 (백엔드 API 호환)
      'equipmentNumber': equipmentNumber,
      'serialNumber': serialNumber,
      'barcode': barcode,
      'quantity': quantity,
      'purchaseDate': purchaseDate?.toIso8601String(),
      'purchasePrice': purchasePrice,
      'inDate': inDate?.toIso8601String(),
      'remark': remark,
      'warrantyLicense': warrantyLicense,
      'warrantyStartDate': warrantyStartDate?.toIso8601String(),
      'warrantyEndDate': warrantyEndDate?.toIso8601String(),
      // 백엔드 API 연동 필드들
      'currentCompanyId': currentCompanyId,
      'warehouseLocationId': warehouseLocationId,
      'currentBranchId': currentBranchId, // Deprecated
      'lastInspectionDate': lastInspectionDate?.toIso8601String(),
      'nextInspectionDate': nextInspectionDate?.toIso8601String(),
      'equipmentStatus': equipmentStatus,
      'companyId': companyId,
      // 레거시 호환성 (하위 호환성 위해 유지)
      'name': equipmentNumber,
      'category': category1,
      'subCategory': category2,
      'subSubCategory': category3,
    };
  }

  factory Equipment.fromJson(Map<String, dynamic> json) {
    return Equipment(
      id: json['id'],
      modelsId: json['models_id'] ?? json['modelsId'],
      model: json['model'] != null ? ModelDto.fromJson(json['model']) : null,
      // 메인 필드들 - 백엔드 우선, 레거시 fallback
      equipmentNumber: json['equipmentNumber'] ?? json['name'] ?? '',
      serialNumber: json['serialNumber'],
      barcode: json['barcode'],
      quantity: json['quantity'] ?? 0,
      purchaseDate: json['purchaseDate'] != null
          ? DateTime.parse(json['purchaseDate'])
          : null,
      purchasePrice: json['purchasePrice']?.toDouble(),
      inDate: json['inDate'] != null ? DateTime.parse(json['inDate']) : null,
      remark: json['remark'],
      warrantyLicense: json['warrantyLicense'],
      warrantyStartDate:
          json['warrantyStartDate'] != null
              ? DateTime.parse(json['warrantyStartDate'])
              : null,
      warrantyEndDate:
          json['warrantyEndDate'] != null
              ? DateTime.parse(json['warrantyEndDate'])
              : null,
      // 백엔드 API 연동 필드들
      currentCompanyId: json['currentCompanyId'],
      warehouseLocationId: json['warehouseLocationId'],
      currentBranchId: json['currentBranchId'], // Deprecated
      lastInspectionDate: json['lastInspectionDate'] != null
          ? DateTime.parse(json['lastInspectionDate'])
          : null,
      nextInspectionDate: json['nextInspectionDate'] != null
          ? DateTime.parse(json['nextInspectionDate'])
          : null,
      equipmentStatus: json['equipmentStatus'],
      companyId: json['companyId'],
    );
  }
}

class EquipmentIn {
  final int? id;
  final Equipment equipment;
  final DateTime inDate;
  final String status; // I (입고)
  final String type; // 장비 유형: '신제품', '중고', '계약'
  final String? warehouseLocation; // 입고지
  final String? partnerCompany; // 파트너사
  final String? remark; // 비고

  EquipmentIn({
    this.id,
    required this.equipment,
    required this.inDate,
    this.status = 'I',
    this.type = EquipmentType.new_, // 기본값은 '신제품'으로 설정
    this.warehouseLocation,
    this.partnerCompany,
    this.remark,
  });

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'equipment': equipment.toJson(),
      'inDate': inDate.toIso8601String(),
      'status': status,
      'type': type,
      'warehouseLocation': warehouseLocation,
      'partnerCompany': partnerCompany,
      'remark': remark,
    };
  }

  factory EquipmentIn.fromJson(Map<String, dynamic> json) {
    return EquipmentIn(
      id: json['id'],
      equipment: Equipment.fromJson(json['equipment']),
      inDate: DateTime.parse(json['inDate']),
      status: json['status'],
      type: json['type'] ?? EquipmentType.new_,
      warehouseLocation: json['warehouseLocation'],
      partnerCompany: json['partnerCompany'],
      remark: json['remark'],
    );
  }
}

class EquipmentOut {
  final int? id;
  final Equipment equipment;
  final DateTime outDate;
  final String status; // O (출고), I (재입고), R (수리)
  final String? company; // 출고 회사
  final String? manager; // 담당자
  final String? license; // 라이센스
  final DateTime? returnDate; // 재입고/수리 날짜
  final String? returnType; // 재입고/수리 유형
  final String? remark; // 비고

  EquipmentOut({
    this.id,
    required this.equipment,
    required this.outDate,
    this.status = 'O',
    this.company,
    this.manager,
    this.license,
    this.returnDate,
    this.returnType,
    this.remark,
  });

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'equipment': equipment.toJson(),
      'outDate': outDate.toIso8601String(),
      'status': status,
      'company': company,
      'manager': manager,
      'license': license,
      'returnDate': returnDate?.toIso8601String(),
      'returnType': returnType,
      'remark': remark,
    };
  }

  factory EquipmentOut.fromJson(Map<String, dynamic> json) {
    return EquipmentOut(
      id: json['id'],
      equipment: Equipment.fromJson(json['equipment']),
      outDate: DateTime.parse(json['outDate']),
      status: json['status'],
      company: json['company'],
      manager: json['manager'],
      license: json['license'],
      returnDate:
          json['returnDate'] != null
              ? DateTime.parse(json['returnDate'])
              : null,
      returnType: json['returnType'],
      remark: json['remark'],
    );
  }
}

class UnifiedEquipment {
  final int? id;
  final Equipment equipment;
  final DateTime date; // 입고일 또는 출고일
  final String
  status; // 상태 코드: 'I'(입고), 'O'(출고), 'R'(수리중), 'D'(손상), 'L'(분실), 'E'(기타)
  final String? notes; // 추가 비고
  final String? _type; // 내부용: 입고 장비 유형
  
  // 백엔드 API 구조 변경으로 추가된 필드들 (리스트 화면용)
  final String? currentCompany; // 현재 회사명
  final String? currentBranch; // 현재 지점명
  final String? warehouseLocation; // 창고 위치
  final DateTime? lastInspectionDate; // 최근 점검일
  final DateTime? nextInspectionDate; // 다음 점검일
  
  // 백엔드에서 직접 제공하는 flat 구조 필드들 (equipment list API)
  final String? companyName; // company_name (백엔드 직접 제공)
  final String? vendorName; // vendor_name (백엔드 직접 제공)  
  final String? modelName; // model_name (백엔드 직접 제공)

  UnifiedEquipment({
    this.id,
    required this.equipment,
    required this.date,
    required this.status,
    this.notes,
    String? type,
    // 새로운 필드들
    this.currentCompany,
    this.currentBranch,
    this.warehouseLocation,
    this.lastInspectionDate,
    this.nextInspectionDate,
    // 백엔드 직접 제공 필드들
    this.companyName,
    this.vendorName,
    this.modelName,
  }) : _type = type;

  // 장비 유형 반환 (입고 장비만)
  String? get type => status == 'I' ? _type : null;

  // 장비 상태 텍스트 변환
  String get statusText {
    switch (status) {
      case EquipmentStatus.in_:
        return '입고';
      case EquipmentStatus.out:
        return '출고';
      case EquipmentStatus.rent:
        return '대여';
      case EquipmentStatus.repair:
        return '수리중';
      case EquipmentStatus.damaged:
        return '손상';
      case EquipmentStatus.lost:
        return '분실';
      case EquipmentStatus.etc:
        return '기타';
      default:
        return '알 수 없음';
    }
  }

  // EquipmentIn 모델에서 변환
  factory UnifiedEquipment.fromEquipmentIn(
    id,
    equipment,
    inDate,
    status, {
    String? type,
  }) {
    return UnifiedEquipment(
      id: id,
      equipment: equipment,
      date: inDate,
      status: status,
      type: type,
    );
  }

  // EquipmentOut 모델에서 변환
  factory UnifiedEquipment.fromEquipmentOut(id, equipment, outDate, status) {
    return UnifiedEquipment(
      id: id,
      equipment: equipment,
      date: outDate,
      status: status,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'equipment': equipment.toJson(),
      'date': date.toIso8601String(),
      'status': status,
      'notes': notes,
      // 새로운 필드들
      'currentCompany': currentCompany,
      'currentBranch': currentBranch,
      'warehouseLocation': warehouseLocation,
      'lastInspectionDate': lastInspectionDate?.toIso8601String(),
      'nextInspectionDate': nextInspectionDate?.toIso8601String(),
      // 백엔드 직접 제공 필드들
      'companyName': companyName,
      'vendorName': vendorName,
      'modelName': modelName,
    };
  }

  factory UnifiedEquipment.fromJson(Map<String, dynamic> json) {
    return UnifiedEquipment(
      id: json['id'],
      equipment: Equipment.fromJson(json['equipment']),
      date: DateTime.parse(json['date']),
      status: json['status'],
      notes: json['notes'],
      // 새로운 필드들
      currentCompany: json['currentCompany'],
      currentBranch: json['currentBranch'], 
      warehouseLocation: json['warehouseLocation'],
      lastInspectionDate: json['lastInspectionDate'] != null
          ? DateTime.parse(json['lastInspectionDate'])
          : null,
      nextInspectionDate: json['nextInspectionDate'] != null
          ? DateTime.parse(json['nextInspectionDate'])
          : null,
      // 백엔드 직접 제공 필드들 (equipment list API에서)
      companyName: json['company_name'],
      vendorName: json['vendor_name'],
      modelName: json['model_name'],
    );
  }
}
