import transferRecordsSeed from '../data/transfer-records.json';
import type { VehicleRecord } from '../types';
import { isEmpty } from './vehicle';

export interface TransferRecordRow {
  id: string;
  plateNo: string;
  transferDate: string;
  transferOutPerson: string;
  recipientPerson: string;
  departureArea: string;
  receivingArea: string;
  transferMethod: string;
  departureParking: string;
  receivingParking: string;
  receiveDate: string;
}

export interface TransferRecordFilters {
  startDate: string;
  endDate: string;
  transferOutPerson: string;
  recipientPerson: string;
}

export const EMPTY_TRANSFER_RECORD_FILTERS: TransferRecordFilters = {
  startDate: '',
  endDate: '',
  transferOutPerson: '',
  recipientPerson: '',
};

const SEED_TRANSFER_RECORDS = transferRecordsSeed as TransferRecordRow[];

function transferDatePart(value: string): string {
  if (isEmpty(value)) return '';
  return String(value).slice(0, 10);
}

export function resolveVehicleTransferRecords(record: VehicleRecord): TransferRecordRow[] {
  return SEED_TRANSFER_RECORDS
    .filter((item) => item.plateNo === record.plateNo)
    .sort((a, b) => String(b.transferDate).localeCompare(String(a.transferDate)));
}

export function buildTransferRecordOptions(
  rows: TransferRecordRow[],
  field: 'transferOutPerson' | 'recipientPerson',
): string[] {
  const values = rows
    .map((row) => row[field])
    .filter((value) => Boolean(value));
  return [...new Set(values)].sort((a, b) => a.localeCompare(b, 'zh-CN'));
}

export function applyTransferRecordFilters(
  rows: TransferRecordRow[],
  filters: TransferRecordFilters,
): TransferRecordRow[] {
  return rows.filter((row) => {
    const date = transferDatePart(row.transferDate);
    if (filters.startDate && date < filters.startDate) return false;
    if (filters.endDate && date > filters.endDate) return false;
    if (filters.transferOutPerson && row.transferOutPerson !== filters.transferOutPerson) return false;
    if (filters.recipientPerson && row.recipientPerson !== filters.recipientPerson) return false;
    return true;
  });
}

export function formatTransferCell(value: string): string {
  return value || '—';
}
