import { apiClient } from './api-client';

// ─── Types ──────────────────────────────────────────────

export type IndustrialParkStatus =
  | 'PLANNING'
  | 'UNDER_CONSTRUCTION'
  | 'OPERATIONAL'
  | 'FULL';

export type VietnamRegion = 'NORTH' | 'CENTRAL' | 'SOUTH';

export interface IndustrialParkListItem {
  id: string;
  name: string;
  nameEn: string | null;
  slug: string;
  developer: string;
  status: IndustrialParkStatus;
  province: string;
  region: VietnamRegion;
  totalAreaHa: number;
  occupancyRate: number;
  remainingAreaHa: number;
  tenantCount: number;
  landRentUsdM2Year: number | null;
  rbfRentUsdM2Month: number | null;
  rbwRentUsdM2Month: number | null;
  targetIndustries: string[];
  latitude: number;
  longitude: number;
}

export interface IndustrialParkDetail {
  id: string;
  name: string;
  nameEn: string | null;
  slug: string;
  developer: string;
  operator: string | null;
  status: IndustrialParkStatus;
  latitude: number;
  longitude: number;
  address: string;
  district: string;
  province: string;
  region: VietnamRegion;
  totalAreaHa: number;
  leasableAreaHa: number;
  occupancyRate: number;
  remainingAreaHa: number;
  tenantCount: number;
  establishedYear: number | null;
  landRentUsdM2Year: number | null;
  rbfRentUsdM2Month: number | null;
  rbwRentUsdM2Month: number | null;
  managementFeeUsd: number | null;
  infrastructure: Record<string, string> | null;
  connectivity: Record<string, { name: string; distanceKm: number }> | null;
  incentives: Record<string, unknown> | null;
  targetIndustries: string[];
  existingTenants: { name: string; country: string; industry: string }[] | null;
  certifications: string[] | null;
  media: { url: string; type: string; caption?: string }[] | null;
  documents: { url: string; name: string }[] | null;
  description: string | null;
  descriptionEn: string | null;
  isVerified: boolean;
  listingCount: number;
  createdAt: string;
  updatedAt: string;
}

export interface IndustrialParkStats {
  totalParks: number;
  totalAreaHa: number;
  avgOccupancyRate: number;
  totalTenants: number;
  byRegion: { region: string; count: number; avgOccupancy: number }[];
  byStatus: { status: string; count: number }[];
  topProvinces: { province: string; count: number; avgRent: number | null }[];
}

export interface IndustrialMarketData {
  totalParks: number;
  avgOccupancyRate: number;
  avgLandRentUsdM2: number | null;
  avgRbfRentUsdM2: number | null;
  rentByRegion: { region: string; avgLandRent: number | null; avgRbfRent: number | null; parkCount: number }[];
  rentByProvince: { province: string; avgLandRent: number | null; avgRbfRent: number | null; parkCount: number }[];
}

export interface PaginatedResult<T> {
  data: T[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

export interface SearchIndustrialParksParams {
  q?: string;
  province?: string;
  region?: VietnamRegion;
  status?: IndustrialParkStatus;
  minAreaHa?: number;
  maxRentUsdM2?: number;
  targetIndustry?: string;
  page?: number;
  limit?: number;
}

// ─── Labels ─────────────────────────────────────────────

export const PARK_STATUS_LABELS: Record<IndustrialParkStatus, string> = {
  PLANNING: 'Quy hoạch',
  UNDER_CONSTRUCTION: 'Đang xây dựng',
  OPERATIONAL: 'Đang hoạt động',
  FULL: 'Đã lấp đầy',
};

export const PARK_STATUS_COLORS: Record<IndustrialParkStatus, string> = {
  PLANNING: 'bg-blue-100 text-blue-800',
  UNDER_CONSTRUCTION: 'bg-amber-100 text-amber-800',
  OPERATIONAL: 'bg-green-100 text-green-800',
  FULL: 'bg-red-100 text-red-800',
};

export const REGION_LABELS: Record<VietnamRegion, string> = {
  NORTH: 'Miền Bắc',
  CENTRAL: 'Miền Trung',
  SOUTH: 'Miền Nam',
};

// ─── API Functions ──────────────────────────────────────

export const industrialApi = {
  search: (params: SearchIndustrialParksParams = {}) => {
    const query = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== '') query.append(key, String(value));
    });
    const qs = query.toString();
    return apiClient.get<PaginatedResult<IndustrialParkListItem>>(
      `/industrial/parks${qs ? `?${qs}` : ''}`,
    );
  },

  getBySlug: (slug: string) =>
    apiClient.get<IndustrialParkDetail>(`/industrial/parks/${slug}`),

  compare: (ids: string[]) =>
    apiClient.post<IndustrialParkDetail[]>('/industrial/parks/compare', { ids }),

  getStats: () =>
    apiClient.get<IndustrialParkStats>('/industrial/parks/stats'),

  getMarket: () =>
    apiClient.get<IndustrialMarketData>('/industrial/market'),
};
