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

export type AccidentLevel = '轻微' | '一般' | '较大' | '重大';
export type AccidentStatus = '已结案' | '处理中';

export interface AccidentRecordRow {
  id: string;
  plateNo: string;
  accidentCode: string;
  accidentTime: string;
  accidentLocation: string;
  accidentType: string;
  customerName: string;
  accidentLevel: AccidentLevel;
  ourDamageAmount: number;
  theirDamageAmount: number;
  responsibility: string;
  status: AccidentStatus;
  closedTime: string;
}

export interface AccidentRecordFilters {
  startDate: string;
  endDate: string;
  customerName: string;
  accidentLevel: string;
  accidentStatus: string;
}

export const EMPTY_ACCIDENT_RECORD_FILTERS: AccidentRecordFilters = {
  startDate: '',
  endDate: '',
  customerName: '',
  accidentLevel: '',
  accidentStatus: '',
};

export const ACCIDENT_LEVEL_OPTIONS: AccidentLevel[] = ['轻微', '一般', '较大', '重大'];
export const ACCIDENT_STATUS_OPTIONS: AccidentStatus[] = ['已结案', '处理中'];

const SEED_ACCIDENT_RECORDS = accidentRecordsSeed as AccidentRecordRow[];

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

export function resolveVehicleAccidentRecords(record: VehicleRecord): AccidentRecordRow[] {
  return SEED_ACCIDENT_RECORDS
    .filter((item) => item.plateNo === record.plateNo)
    .sort((a, b) => String(b.accidentTime).localeCompare(String(a.accidentTime)));
}

export function buildAccidentRecordOptions(
  rows: AccidentRecordRow[],
  field: 'customerName' | 'accidentLevel' | 'status',
): 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 applyAccidentRecordFilters(
  rows: AccidentRecordRow[],
  filters: AccidentRecordFilters,
): AccidentRecordRow[] {
  return rows.filter((row) => {
    const date = accidentDatePart(row.accidentTime);
    if (filters.startDate && date < filters.startDate) return false;
    if (filters.endDate && date > filters.endDate) return false;
    if (filters.customerName && row.customerName !== filters.customerName) return false;
    if (filters.accidentLevel && row.accidentLevel !== filters.accidentLevel) return false;
    if (filters.accidentStatus && row.status !== filters.accidentStatus) return false;
    return true;
  });
}

export function formatAccidentAmount(value: number): string {
  if (value === null || value === undefined || Number.isNaN(value)) return '—';
  return value.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
}

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

export function accidentStatusTone(status: AccidentStatus): 'green' | 'amber' {
  return status === '已结案' ? 'green' : 'amber';
}
