import annualReviewRecordsSeed from '../data/annual-review-records.json';
import type { VehicleRecord } from '../types';
import { isEmpty } from './vehicle';

export interface AnnualReviewRecordRow {
  id: string;
  plateNo: string;
  inspectionValidUntil: string;
  inspectionStation: string;
  inspectionCost: number | null;
  m2Station: string;
  m2Cost: number | null;
  zbStation: string;
  zbCost: number | null;
  executor: string;
  executeTime: string;
}

export interface AnnualReviewRecordFilters {
  executeStartDate: string;
  executeEndDate: string;
  validStartDate: string;
  validEndDate: string;
  executor: string;
}

export const EMPTY_ANNUAL_REVIEW_RECORD_FILTERS: AnnualReviewRecordFilters = {
  executeStartDate: '',
  executeEndDate: '',
  validStartDate: '',
  validEndDate: '',
  executor: '',
};

const SEED_ANNUAL_REVIEW_RECORDS = annualReviewRecordsSeed as AnnualReviewRecordRow[];

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

export function resolveVehicleAnnualReviewRecords(record: VehicleRecord): AnnualReviewRecordRow[] {
  return SEED_ANNUAL_REVIEW_RECORDS
    .filter((item) => item.plateNo === record.plateNo)
    .sort((a, b) => String(b.executeTime).localeCompare(String(a.executeTime)));
}

export function buildAnnualReviewRecordOptions(
  rows: AnnualReviewRecordRow[],
  field: 'executor',
): 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 applyAnnualReviewRecordFilters(
  rows: AnnualReviewRecordRow[],
  filters: AnnualReviewRecordFilters,
): AnnualReviewRecordRow[] {
  return rows.filter((row) => {
    const executeDate = datePart(row.executeTime);
    if (filters.executeStartDate && executeDate < filters.executeStartDate) return false;
    if (filters.executeEndDate && executeDate > filters.executeEndDate) return false;

    const validDate = datePart(row.inspectionValidUntil);
    if (filters.validStartDate && validDate < filters.validStartDate) return false;
    if (filters.validEndDate && validDate > filters.validEndDate) return false;

    if (filters.executor && row.executor !== filters.executor) return false;
    return true;
  });
}

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

export function formatAnnualReviewMoney(cost: number | null | undefined): string {
  if (cost == null) return '—';
  return cost.toFixed(2);
}
