class CompanyBrand {
  final String displayName;
  final String? logoUrl;
  final String subdomain;
  final double? marketplaceRating;
  final String primaryColor;

  const CompanyBrand({
    required this.displayName,
    this.logoUrl,
    required this.subdomain,
    this.marketplaceRating,
    required this.primaryColor,
  });

  factory CompanyBrand.fromJson(Map<String, dynamic> json) => CompanyBrand(
        displayName: json['displayName'] as String? ?? '',
        logoUrl: json['logoUrl'] as String?,
        subdomain: json['subdomain'] as String? ?? '',
        marketplaceRating:
            (json['marketplaceRating'] as num?)?.toDouble(),
        primaryColor: json['primaryColor'] as String? ?? '#1A56DB',
      );
}

class MarketplaceCompany {
  final String id;
  final CompanyBrand brand;

  const MarketplaceCompany({required this.id, required this.brand});

  factory MarketplaceCompany.fromJson(Map<String, dynamic> json) =>
      MarketplaceCompany(
        id: json['id'] as String,
        brand: CompanyBrand.fromJson(
            json['brand'] as Map<String, dynamic>),
      );
}

class MarketplaceVehicle {
  final String id;
  final String companyId;
  final String make;
  final String model;
  final int year;
  final String? color;
  final String licensePlate;
  final String category;
  final int seats;
  final String transmission;
  final String fuelType;
  final List<String> features;
  // dailyRate comes in cents from the API
  final int dailyRateCents;
  final String status;
  final List<String> photos;
  final int? mileage;
  final bool isPublished;
  final MarketplaceCompany company;
  final bool availability;
  final String availabilityStatus;
  final DateTime? nextAvailableAt;

  const MarketplaceVehicle({
    required this.id,
    required this.companyId,
    required this.make,
    required this.model,
    required this.year,
    this.color,
    required this.licensePlate,
    required this.category,
    required this.seats,
    required this.transmission,
    required this.fuelType,
    required this.features,
    required this.dailyRateCents,
    required this.status,
    required this.photos,
    this.mileage,
    required this.isPublished,
    required this.company,
    required this.availability,
    required this.availabilityStatus,
    this.nextAvailableAt,
  });

  String get displayName => '$year $make $model';
  String? get primaryPhoto => photos.isNotEmpty ? photos.first : null;
  // Convert cents to dollars for display
  double get dailyRate => dailyRateCents / 100;
  String get companySlug => company.brand.subdomain;

  factory MarketplaceVehicle.fromJson(Map<String, dynamic> json) =>
      MarketplaceVehicle(
        id: json['id'] as String,
        companyId: json['companyId'] as String,
        make: json['make'] as String,
        model: json['model'] as String,
        year: json['year'] as int,
        color: json['color'] as String?,
        licensePlate: json['licensePlate'] as String,
        category: json['category'] as String? ?? 'ECONOMY',
        seats: json['seats'] as int? ?? 5,
        transmission: json['transmission'] as String? ?? 'MANUAL',
        fuelType: json['fuelType'] as String? ?? 'GASOLINE',
        features: (json['features'] as List<dynamic>?)
                ?.map((e) => e as String)
                .toList() ??
            [],
        dailyRateCents: json['dailyRate'] as int? ?? 0,
        status: json['status'] as String? ?? 'AVAILABLE',
        photos: (json['photos'] as List<dynamic>?)
                ?.map((e) => e as String)
                .toList() ??
            [],
        mileage: json['mileage'] as int?,
        isPublished: json['isPublished'] as bool? ?? false,
        company: MarketplaceCompany.fromJson(
            json['company'] as Map<String, dynamic>),
        availability: json['availability'] as bool? ?? true,
        availabilityStatus:
            json['availabilityStatus'] as String? ?? 'AVAILABLE',
        nextAvailableAt: json['nextAvailableAt'] != null
            ? DateTime.tryParse(json['nextAvailableAt'] as String)
            : null,
      );
}

class MarketplaceSearchResult {
  final List<MarketplaceVehicle> data;
  final int total;
  final int page;
  final int pageSize;

  const MarketplaceSearchResult({
    required this.data,
    required this.total,
    required this.page,
    required this.pageSize,
  });

  factory MarketplaceSearchResult.fromJson(Map<String, dynamic> json) {
    final raw = json['data'] ?? json;
    if (raw is List) {
      return MarketplaceSearchResult(
        data: raw
            .map((e) =>
                MarketplaceVehicle.fromJson(e as Map<String, dynamic>))
            .toList(),
        total: json['total'] as int? ?? raw.length,
        page: json['page'] as int? ?? 1,
        pageSize: json['pageSize'] as int? ?? 20,
      );
    }
    return MarketplaceSearchResult(
      data: (json['data'] as List<dynamic>)
          .map((e) =>
              MarketplaceVehicle.fromJson(e as Map<String, dynamic>))
          .toList(),
      total: json['total'] as int? ?? 0,
      page: json['page'] as int? ?? 1,
      pageSize: json['pageSize'] as int? ?? 20,
    );
  }
}

class MarketplaceOffer {
  final String id;
  final String title;
  final String? description;
  final String? imageUrl;
  final String type;
  final int discountValue;
  final String? promoCode;
  final bool isFeatured;
  final DateTime validUntil;
  final MarketplaceCompany company;

  const MarketplaceOffer({
    required this.id,
    required this.title,
    this.description,
    this.imageUrl,
    required this.type,
    required this.discountValue,
    this.promoCode,
    required this.isFeatured,
    required this.validUntil,
    required this.company,
  });

  String get discountLabel {
    switch (type) {
      case 'PERCENTAGE':
        return '$discountValue% off';
      case 'FIXED_AMOUNT':
        return '\$${(discountValue / 100).toStringAsFixed(0)} off';
      case 'FREE_DAY':
        return '$discountValue free day(s)';
      case 'SPECIAL_RATE':
        return 'Special rate';
      default:
        return 'Offer';
    }
  }

  factory MarketplaceOffer.fromJson(Map<String, dynamic> json) =>
      MarketplaceOffer(
        id: json['id'] as String,
        title: json['title'] as String,
        description: json['description'] as String?,
        imageUrl: json['imageUrl'] as String?,
        type: json['type'] as String,
        discountValue: json['discountValue'] as int? ?? 0,
        promoCode: json['promoCode'] as String?,
        isFeatured: json['isFeatured'] as bool? ?? false,
        validUntil:
            DateTime.parse(json['validUntil'] as String),
        company: MarketplaceCompany.fromJson(
            json['company'] as Map<String, dynamic>),
      );
}
