import insurancePurchasesSeed from '../data/insurance-purchases.json';
import vehicleInsuranceLedgerSeed from '../data/vehicle-insurance-ledger.json';
import type { InsurancePurchaseRecord, InsuranceType, VehicleRecord } from '../types';
import { daysUntilExpire } from './vehicle';
import { getInsuranceCoverageState } from './insurance';

export type VehicleInsuranceTypeKey =
  | 'compulsory'
  | 'commercial'
  | 'excess'
  | 'cargo'
  | 'driverAccident';

export type InsurancePolicyTag = '' | 'suspended' | 'cancelled';

export interface VehicleInsuranceTypeDef {
  key: VehicleInsuranceTypeKey;
  label: string;
  purchaseType?: InsuranceType;
}

export const VEHICLE_INSURANCE_TYPES: VehicleInsuranceTypeDef[] = [
  { key: 'compulsory', label: '交强险', purchaseType: '交强险' },
  { key: 'commercial', label: '商业险', purchaseType: '商业险' },
  { key: 'excess', label: '超赔险' },
  { key: 'driverAccident', label: '驾意险' },
  { key: 'cargo', label: '货物险' },
];

export interface InsuranceLedgerEnrichment {
  policyNo?: string;
  company?: string;
  premium?: string;
  expireDate?: string;
  purchasedAt?: string;
  operator?: string;
  policyTag?: InsurancePolicyTag;
}

export interface InsuranceHistoryRow {
  id: string;
  purchaseTime: string;
  operator: string;
  purchaseType: '新保' | '续保' | '停保' | '复驶' | '退保';
  policyNo: string;
  policyStatus: '正常' | '已停保' | '已退保';
  company: string;
  payTime: string;
  expireDate: string;
  remainText: string;
  policyFileName: string | null;
}

export interface InsuranceTypeCoverage {
  key: VehicleInsuranceTypeKey;
  label: string;
  status: 'not_purchased' | 'valid' | 'warning' | 'expired' | 'suspended' | 'cancelled';
  statusLabel: string;
  remainText: string;
  policyNo: string;
  company: string;
  expireDate: string;
  premium: string;
  history: InsuranceHistoryRow[];
}

export interface VehicleInsuranceOverview {
  overallLabel: string;
  overallTone: 'green' | 'amber' | 'red';
  overallTip: string;
  types: InsuranceTypeCoverage[];
}

const ALL_PURCHASES = insurancePurchasesSeed as InsurancePurchaseRecord[];
const LEDGER_SEED = vehicleInsuranceLedgerSeed as Record<
  string,
  Partial<Record<VehicleInsuranceTypeKey, InsuranceLedgerEnrichment>>
>;

const INSURANCE_WARN_DAYS = 30;
const DEMO_OPERATORS = ['张明辉', '李专员', '王专员', '张小凡', '张三', '赵六', '陈高伟'];

function resolveOperator(seed: string, fallback?: string): string {
  if (fallback) return fallback;
  let hash = 0;
  for (let i = 0; i < seed.length; i += 1) {
    hash = (hash + seed.charCodeAt(i)) % DEMO_OPERATORS.length;
  }
  return DEMO_OPERATORS[hash] ?? '—';
}

function ledgerForVehicle(vehicleId: string): Partial<Record<VehicleInsuranceTypeKey, InsuranceLedgerEnrichment>> {
  return LEDGER_SEED[vehicleId] ?? {};
}

function purchasesForVehicle(vehicleId: string): InsurancePurchaseRecord[] {
  return ALL_PURCHASES.filter((item) => item.vehicleId === vehicleId);
}

function isNewerPurchase(candidate: InsurancePurchaseRecord, current: InsurancePurchaseRecord): boolean {
  const candidateAt = candidate.purchasedAt || candidate.expireDate;
  const currentAt = current.purchasedAt || current.expireDate;
  if (candidateAt !== currentAt) return candidateAt > currentAt;
  return candidate.id > current.id;
}

function resolvePolicyTag(enrichment?: InsuranceLedgerEnrichment): InsurancePolicyTag {
  return enrichment?.policyTag ?? '';
}

function resolvePolicyStatus(
  expireDate: string,
  policyTag: InsurancePolicyTag,
): { status: InsuranceTypeCoverage['status']; policyStatus: InsuranceHistoryRow['policyStatus'] } {
  if (policyTag === 'cancelled') {
    return { status: 'cancelled', policyStatus: '已退保' };
  }
  if (policyTag === 'suspended') {
    return { status: 'suspended', policyStatus: '已停保' };
  }
  const coverage = getInsuranceCoverageState(expireDate);
  if (coverage === 'not_purchased') {
    return { status: 'not_purchased', policyStatus: '正常' };
  }
  if (coverage === 'expired') {
    return { status: 'expired', policyStatus: '正常' };
  }
  const days = daysUntilExpire(expireDate);
  if (days !== null && days <= INSURANCE_WARN_DAYS) {
    return { status: 'warning', policyStatus: '正常' };
  }
  return { status: 'valid', policyStatus: '正常' };
}

function buildRemainText(status: InsuranceTypeCoverage['status'], expireDate: string): string {
  if (status === 'not_purchased') return '未购买';
  if (status === 'cancelled') return '已退保';
  if (status === 'suspended') return '已停保';
  const days = daysUntilExpire(expireDate);
  if (days === null) return '—';
  if (days < 0) return `过期${Math.abs(days)}天`;
  return `剩余${days}天`;
}

function buildStatusLabel(status: InsuranceTypeCoverage['status'], expireDate: string): string {
  if (status === 'not_purchased') return '未购买';
  if (status === 'cancelled') return '已退保';
  if (status === 'suspended') return '已停保';
  const days = daysUntilExpire(expireDate);
  if (status === 'expired' || (days !== null && days < 0)) {
    return days !== null ? `已到期 (逾期 ${Math.abs(days)} 天)` : '已到期';
  }
  if (status === 'warning' || (days !== null && days <= INSURANCE_WARN_DAYS)) {
    return days !== null ? `临期 (${days} 天后)` : '临期';
  }
  return '正常';
}

function buildPolicyFileName(typeLabel: string, policyNo: string): string | null {
  if (!policyNo || policyNo === '—') return null;
  return `${typeLabel}_${policyNo}.pdf`;
}

function buildHistoryRows(
  vehicleId: string,
  typeKey: VehicleInsuranceTypeKey,
  typeDef: VehicleInsuranceTypeDef,
  enrichment?: InsuranceLedgerEnrichment,
): InsuranceHistoryRow[] {
  const rows: InsuranceHistoryRow[] = [];
  const purchaseType = typeDef.purchaseType;

  if (purchaseType) {
    const related = purchasesForVehicle(vehicleId)
      .filter((item) => item.insuranceType === purchaseType)
      .sort((a, b) => String(a.purchasedAt).localeCompare(String(b.purchasedAt)));

    related.forEach((purchase, index) => {
      const policyTag = index === related.length - 1 ? resolvePolicyTag(enrichment) : '';
      const { status, policyStatus } = resolvePolicyStatus(purchase.expireDate, policyTag);
      const policyNo = enrichment?.policyNo && index === related.length - 1
        ? enrichment.policyNo
        : `POL-${purchase.id}`;
      rows.push({
        id: purchase.id,
        purchaseTime: purchase.purchasedAt,
        operator: resolveOperator(
          purchase.id,
          enrichment?.operator && index === related.length - 1 ? enrichment.operator : undefined,
        ),
        purchaseType: index === 0 ? '新保' : '续保',
        policyNo,
        policyStatus,
        company: enrichment?.company && index === related.length - 1 ? enrichment.company : '—',
        payTime: purchase.purchasedAt,
        expireDate: purchase.expireDate,
        remainText: buildRemainText(status, purchase.expireDate),
        policyFileName: buildPolicyFileName(typeDef.label, policyNo),
      });
    });
  }

  if (!rows.length && enrichment?.expireDate) {
    const policyTag = resolvePolicyTag(enrichment);
    const { status, policyStatus } = resolvePolicyStatus(enrichment.expireDate, policyTag);
    rows.push({
      id: `${vehicleId}-${typeKey}-seed`,
      purchaseTime: enrichment.purchasedAt || enrichment.expireDate,
      operator: resolveOperator(`${vehicleId}-${typeKey}-seed`, enrichment.operator),
      purchaseType: '新保',
      policyNo: enrichment.policyNo || '—',
      policyStatus,
      company: enrichment.company || '—',
      payTime: enrichment.purchasedAt || enrichment.expireDate,
      expireDate: enrichment.expireDate,
      remainText: buildRemainText(status, enrichment.expireDate),
      policyFileName: buildPolicyFileName(typeDef.label, enrichment.policyNo || ''),
    });
  }

  return rows.sort((a, b) => String(b.purchaseTime).localeCompare(String(a.purchaseTime)));
}

function buildTypeCoverage(
  vehicleId: string,
  typeDef: VehicleInsuranceTypeDef,
  enrichment?: InsuranceLedgerEnrichment,
): InsuranceTypeCoverage {
  const history = buildHistoryRows(vehicleId, typeDef.key, typeDef, enrichment);
  const latestPurchase = typeDef.purchaseType
    ? purchasesForVehicle(vehicleId)
      .filter((item) => item.insuranceType === typeDef.purchaseType)
      .reduce<InsurancePurchaseRecord | undefined>((latest, item) => (
        !latest || isNewerPurchase(item, latest) ? item : latest
      ), undefined)
    : undefined;

  const expireDate = latestPurchase?.expireDate || enrichment?.expireDate || '';
  const hasPolicy = Boolean(latestPurchase || enrichment?.policyNo || enrichment?.expireDate);
  const policyTag = resolvePolicyTag(enrichment);
  const { status } = hasPolicy
    ? resolvePolicyStatus(expireDate, policyTag)
    : { status: 'not_purchased' as const };

  return {
    key: typeDef.key,
    label: typeDef.label,
    status: hasPolicy ? status : 'not_purchased',
    statusLabel: buildStatusLabel(hasPolicy ? status : 'not_purchased', expireDate),
    remainText: buildRemainText(hasPolicy ? status : 'not_purchased', expireDate),
    policyNo: enrichment?.policyNo || (latestPurchase ? `POL-${latestPurchase.id}` : ''),
    company: enrichment?.company || '—',
    expireDate,
    premium: enrichment?.premium || '—',
    history,
  };
}

function buildOverallStatus(types: InsuranceTypeCoverage[]): Pick<VehicleInsuranceOverview, 'overallLabel' | 'overallTone' | 'overallTip'> {
  const compulsory = types.find((item) => item.key === 'compulsory');
  const commercial = types.find((item) => item.key === 'commercial');

  const isValid = (item?: InsuranceTypeCoverage) => (
    item?.status === 'valid' || item?.status === 'warning' || item?.status === 'suspended'
  );

  const isNormal = isValid(compulsory) && isValid(commercial);
  if (isNormal) {
    const hasWarning = compulsory?.status === 'warning' || commercial?.status === 'warning';
    return {
      overallLabel: hasWarning ? '临期' : '正常',
      overallTone: hasWarning ? 'amber' : 'green',
      overallTip: hasWarning
        ? '交强险或商业险临期，仍在有效期内，可交车但需尽快续保'
        : '交强险、商业险均在有效期内',
    };
  }

  const reasons: string[] = [];
  if (!compulsory || compulsory.status === 'not_purchased' || compulsory.status === 'cancelled') {
    reasons.push('交强险未购买');
  } else if (compulsory.status === 'expired') {
    reasons.push('交强险已到期');
  }
  if (!commercial || commercial.status === 'not_purchased' || commercial.status === 'cancelled') {
    reasons.push('商业险未购买');
  } else if (commercial.status === 'expired') {
    reasons.push('商业险已到期');
  }

  return {
    overallLabel: '异常',
    overallTone: 'red',
    overallTip: `${reasons.join('；')}。保险状态异常的车辆禁止交车`,
  };
}

export function resolveVehicleInsuranceOverview(record: VehicleRecord): VehicleInsuranceOverview {
  const ledger = ledgerForVehicle(record.id);
  const types = VEHICLE_INSURANCE_TYPES.map((typeDef) => (
    buildTypeCoverage(record.id, typeDef, ledger[typeDef.key])
  ));
  return {
    ...buildOverallStatus(types),
    types,
  };
}

export function insuranceStatusTone(status: InsuranceTypeCoverage['status']): 'green' | 'amber' | 'red' | 'gray' {
  if (status === 'not_purchased') return 'amber';
  if (status === 'valid') return 'green';
  if (status === 'warning' || status === 'suspended') return 'amber';
  if (status === 'expired') return 'red';
  return 'gray';
}

export function purchaseTypeTone(type: InsuranceHistoryRow['purchaseType']): 'green' | 'blue' | 'amber' | 'gray' {
  if (type === '新保') return 'green';
  if (type === '续保') return 'blue';
  if (type === '停保' || type === '退保') return 'gray';
  return 'amber';
}
