/**
 * @name 车辆管理
 */

import './style.css';
import React, { useCallback, useMemo, useState } from 'react';
import { Download, FileUp } from 'lucide-react';
import seedVehicles from './data/vehicles.json';
import seedInsurancePurchases from './data/insurance-purchases.json';
import { FilterPanel } from './components/FilterPanel';
import { ImportModal } from './components/ImportModal';
import { KpiCards } from './components/KpiCards';
import { OpsManagerModal } from './components/OpsManagerModal';
import { OperateCityEditModal } from './components/OperateCityEditModal';
import { LocationMapModal } from './components/LocationMapModal';
import { VehicleEditModal } from './components/VehicleEditModal';
import { RequirementsModal } from './components/RequirementsModal';
import { PageDocToolbar } from './components/PageDocToolbar';
import { VehicleTable } from './components/VehicleTable';
import { TablePagination } from './components/TablePagination';
import { DetailPage } from './pages/DetailPage';
import {
  EMPTY_FILTERS,
  type KpiKey,
  type VehicleFilters,
  type VehicleRecord,
} from './types';
import type { InsurancePurchaseRecord } from './types';
import { applyFilters } from './utils/filters';
import { buildInsuranceExpireMap } from './utils/insurance';
import type { LeaseRecordRow } from './utils/leaseRecords';
import type { AccidentRecordRow } from './utils/accidentRecords';
import type { ViolationRecordRow } from './utils/violationRecords';
import type { MovementRecordRow } from './utils/movementRecords';
import type { TransferRecordRow } from './utils/transferRecords';
import type { AnnualReviewRecordRow } from './utils/annualReviewRecords';
import { downloadVehiclePrdMarkdownFiles } from './utils/prdDownloads';
import { downloadVehicleTestCasesExcel } from './utils/testCaseExport';
import { countKpi } from './utils/vehicle';

const CAN_EDIT_OPS_MANAGER = true;
const IS_ADMIN = true;
const DEFAULT_PAGE_SIZE = 10;

export default function VehicleManagementApp() {
  const [records, setRecords] = useState<VehicleRecord[]>(seedVehicles as VehicleRecord[]);
  const [pendingFilters, setPendingFilters] = useState<VehicleFilters>(EMPTY_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<VehicleFilters>(EMPTY_FILTERS);
  const [kpiTab, setKpiTab] = useState<KpiKey>('all');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
  const [detailRecord, setDetailRecord] = useState<VehicleRecord | null>(null);
  const [importOpen, setImportOpen] = useState(false);
  const [opsRecord, setOpsRecord] = useState<VehicleRecord | null>(null);
  const [operateCityRecord, setOperateCityRecord] = useState<VehicleRecord | null>(null);
  const [locationMapRecord, setLocationMapRecord] = useState<VehicleRecord | null>(null);
  const [editRecord, setEditRecord] = useState<VehicleRecord | null>(null);
  const [requirementsOpen, setRequirementsOpen] = useState(false);
  const [toast, setToast] = useState('');

  const showToast = useCallback((msg: string) => {
    setToast(msg);
    window.setTimeout(() => setToast(''), 3000);
  }, []);

  const insuranceExpireMap = useMemo(
    () => buildInsuranceExpireMap(seedInsurancePurchases as InsurancePurchaseRecord[]),
    [],
  );

  const kpiCounts = useMemo(() => ({
    all: countKpi(records, 'all'),
    lease: countKpi(records, 'lease'),
    self: countKpi(records, 'self'),
    stock: countKpi(records, 'stock'),
    nonOperating: countKpi(records, 'nonOperating'),
    exit: countKpi(records, 'exit'),
    licenseAbnormal: countKpi(records, 'licenseAbnormal'),
    insuranceAbnormal: countKpi(records, 'insuranceAbnormal'),
  }), [records]);

  const filtered = useMemo(
    () => applyFilters(records, appliedFilters, kpiTab),
    [records, appliedFilters, kpiTab],
  );

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const paged = useMemo(() => {
    const start = (page - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, page, pageSize]);

  const handlePageSizeChange = (size: number) => {
    setPageSize(size);
    setPage(1);
  };

  const handleSearch = () => {
    setAppliedFilters(pendingFilters);
    setPage(1);
  };

  const handleReset = () => {
    setPendingFilters(EMPTY_FILTERS);
    setAppliedFilters(EMPTY_FILTERS);
    setPage(1);
  };

  const handleExport = () => {
    showToast(`导出功能（原型演示）：当前列表共 ${filtered.length} 条`);
  };

  const handleImport = (file: File) => {
    showToast(`已接收文件 ${file.name}，导入校验为原型演示`);
    setImportOpen(false);
  };

  const handleSaveOps = (managers: string[]) => {
    if (!opsRecord) return;
    setRecords((prev) => prev.map((r) => (
      r.id === opsRecord.id ? { ...r, opsManagers: managers } : r
    )));
    setOpsRecord(null);
    showToast('运维负责人已更新');
  };

  const handleSaveOperateCity = (location: string) => {
    if (!operateCityRecord) return;
    setRecords((prev) => prev.map((r) => (
      r.id === operateCityRecord.id
        ? { ...r, location, operateCitySource: '人工' as const }
        : r
    )));
    setOperateCityRecord(null);
    showToast('运营城市已更新');
  };

  const handleOpenContract = (_record: VehicleRecord, contractNo: string) => {
    showToast(`即将跳转至合同详情（原型演示）：${contractNo}`);
  };

  const handleOpenLeaseContract = (record: VehicleRecord, contractNo: string) => {
    showToast(`即将跳转至租赁合同详情（原型演示）：${record.plateNo} · ${contractNo}`);
  };

  const handleOpenDeliveryRecord = (record: VehicleRecord, row: LeaseRecordRow) => {
    showToast(`即将跳转至交车管理详情（原型演示）：${record.plateNo} · ${row.contractNo} · ${row.deliveryDate}`);
  };

  const handleOpenReturnRecord = (record: VehicleRecord, row: LeaseRecordRow) => {
    showToast(`即将跳转至还车管理详情（原型演示）：${record.plateNo} · ${row.contractNo} · ${row.returnDate}`);
  };

  const handleOpenLicenseEdit = (record: VehicleRecord) => {
    showToast(`即将跳转至证照管理编辑页（原型演示）：${record.plateNo}`);
  };

  const handleOpenInsurancePurchase = (record: VehicleRecord, insuranceLabel: string) => {
    showToast(`即将跳转至保险采购编辑页（原型演示）：${record.plateNo} · ${insuranceLabel}`);
  };

  const handleViewFaultDetail = (record: VehicleRecord, row: { faultNo: string }) => {
    showToast(`即将跳转至故障管理详情页（原型演示）：${row.faultNo}`);
  };

  const handleEditFaultRecord = (record: VehicleRecord, row: { faultNo: string }) => {
    showToast(`编辑故障记录（原型演示）：${record.plateNo} · ${row.faultNo}`);
  };

  const handleOpenAccidentDetail = (record: VehicleRecord, row: AccidentRecordRow) => {
    showToast(`即将跳转至事故管理详情页（原型演示）：${row.accidentCode}`);
  };

  const handleOpenViolationDetail = (_record: VehicleRecord, row: ViolationRecordRow) => {
    showToast(`即将跳转至违章管理详情页（原型演示）：${row.violationTime}`);
  };

  const handleOpenMovementDetail = (_record: VehicleRecord, row: MovementRecordRow) => {
    showToast(`即将跳转至异动管理详情页（原型演示）：${row.startDate}`);
  };

  const handleOpenTransferDetail = (_record: VehicleRecord, row: TransferRecordRow) => {
    showToast(`即将跳转至车辆调拨详情页（原型演示）：${row.transferDate}`);
  };

  const handleOpenAnnualReviewDetail = (_record: VehicleRecord, row: AnnualReviewRecordRow) => {
    showToast(`即将跳转至年审管理详情页（原型演示）：${row.inspectionValidUntil}`);
  };

  const handlePreviewPolicyFile = (fileName: string) => {
    showToast(`预览保单文件（原型演示）：${fileName}`);
  };

  const handleDownloadPolicyFile = (fileName: string) => {
    showToast(`已开始下载：${fileName}（原型演示）`);
  };

  const handleOpenDeliveryManagement = (record: VehicleRecord) => {
    showToast(`即将跳转至交车管理（原型演示）：${record.plateNo}`);
  };

  const handleOpenReturnManagement = (record: VehicleRecord) => {
    showToast(`即将跳转至还车管理（原型演示）：${record.plateNo}`);
  };

  const handleSaveEdit = (record: VehicleRecord) => {
    setRecords((prev) => prev.map((r) => (r.id === record.id ? record : r)));
    setEditRecord(null);
    showToast('车辆信息已更新');
  };

  const handleDetailFieldSave = (recordId: string, patch: Partial<VehicleRecord>) => {
    setRecords((prev) => prev.map((r) => (r.id === recordId ? { ...r, ...patch } : r)));
    showToast('车辆信息已更新');
  };

  const handleDownloadPrd = () => {
    downloadVehiclePrdMarkdownFiles(showToast);
  };

  const handleDownloadTestCases = () => {
    downloadVehicleTestCasesExcel(showToast);
  };

  const docToolbar = (
    <PageDocToolbar
      onOpenRequirements={() => setRequirementsOpen(true)}
      onDownloadPrd={handleDownloadPrd}
      onDownloadTestCases={handleDownloadTestCases}
    />
  );

  const activeDetail = detailRecord
    ? records.find((r) => r.id === detailRecord.id) ?? detailRecord
    : null;

  if (activeDetail) {
    return (
      <div className="vm-page">
        {docToolbar}
        <DetailPage
          record={activeDetail}
          onBack={() => setDetailRecord(null)}
          canEditOpsManager={CAN_EDIT_OPS_MANAGER}
          onEditOpsManager={setOpsRecord}
          onEditOperateCity={setOperateCityRecord}
          onOpenLicenseEdit={handleOpenLicenseEdit}
          onSaveField={handleDetailFieldSave}
          onOpenLeaseContract={handleOpenLeaseContract}
          onOpenDeliveryRecord={handleOpenDeliveryRecord}
          onOpenReturnRecord={handleOpenReturnRecord}
          onOpenInsurancePurchase={handleOpenInsurancePurchase}
          onViewFaultDetail={handleViewFaultDetail}
          onEditFaultRecord={handleEditFaultRecord}
          onOpenAccidentDetail={handleOpenAccidentDetail}
          onOpenViolationDetail={handleOpenViolationDetail}
          onOpenMovementDetail={handleOpenMovementDetail}
          onOpenTransferDetail={handleOpenTransferDetail}
          onOpenAnnualReviewDetail={handleOpenAnnualReviewDetail}
          onPreviewPolicyFile={handlePreviewPolicyFile}
          onDownloadPolicyFile={handleDownloadPolicyFile}
        />
        <OpsManagerModal
          open={!!opsRecord}
          record={opsRecord}
          onClose={() => setOpsRecord(null)}
          onSave={handleSaveOps}
        />
        <OperateCityEditModal
          open={!!operateCityRecord}
          record={operateCityRecord}
          records={records}
          onClose={() => setOperateCityRecord(null)}
          onSave={handleSaveOperateCity}
        />
        <RequirementsModal
          open={requirementsOpen}
          variant="detail"
          onClose={() => setRequirementsOpen(false)}
        />
        {toast && <div className="vm-toast" role="status">{toast}</div>}
      </div>
    );
  }

  return (
    <div className="vm-page">
      {docToolbar}
      <FilterPanel
        records={records}
        filters={pendingFilters}
        onChange={(patch) => setPendingFilters((prev) => ({ ...prev, ...patch }))}
        onReset={handleReset}
        onSearch={handleSearch}
      />

      <KpiCards counts={kpiCounts} active={kpiTab} onChange={(key) => { setKpiTab(key); setPage(1); }} />

      <section className="vm-table-section">
        <div className="vm-table-toolbar">
          <div className="vm-table-actions">
            <button type="button" className="vm-btn vm-btn-ghost" onClick={handleExport}>
              <Download size={16} aria-hidden />
              导出
            </button>
            <button type="button" className="vm-btn vm-btn-secondary" onClick={() => setImportOpen(true)}>
              <FileUp size={16} aria-hidden />
              批量导入
            </button>
          </div>
        </div>

        <div className="vm-table-card">
          <VehicleTable
            records={paged}
            insuranceExpireMap={insuranceExpireMap}
            canEditOpsManager={CAN_EDIT_OPS_MANAGER}
            isAdmin={IS_ADMIN}
            onView={setDetailRecord}
            onEdit={setEditRecord}
            onEditOpsManager={setOpsRecord}
            onEditOperateCity={setOperateCityRecord}
            onOpenContract={handleOpenContract}
            onOpenLicenseEdit={handleOpenLicenseEdit}
            onOpenInsurancePurchase={handleOpenInsurancePurchase}
            onOpenLocationMap={setLocationMapRecord}
            onOpenDeliveryManagement={handleOpenDeliveryManagement}
            onOpenReturnManagement={handleOpenReturnManagement}
          />
          <div className="vm-table-footer">
            <TablePagination
              page={Math.min(page, totalPages)}
              pageSize={pageSize}
              total={filtered.length}
              onPageChange={setPage}
              onPageSizeChange={handlePageSizeChange}
            />
          </div>
        </div>
      </section>

      <ImportModal open={importOpen} onClose={() => setImportOpen(false)} onImport={handleImport} />
      <OpsManagerModal
        open={!!opsRecord}
        record={opsRecord}
        onClose={() => setOpsRecord(null)}
        onSave={handleSaveOps}
      />
      <OperateCityEditModal
        open={!!operateCityRecord}
        record={operateCityRecord}
        records={records}
        onClose={() => setOperateCityRecord(null)}
        onSave={handleSaveOperateCity}
      />
      <LocationMapModal
        open={!!locationMapRecord}
        record={locationMapRecord}
        onClose={() => setLocationMapRecord(null)}
      />
      <VehicleEditModal
        open={!!editRecord}
        record={editRecord}
        records={records}
        onClose={() => setEditRecord(null)}
        onSave={handleSaveEdit}
      />

      <RequirementsModal
        open={requirementsOpen}
        variant="list"
        onClose={() => setRequirementsOpen(false)}
      />

      {toast && <div className="vm-toast" role="status" aria-live="polite">{toast}</div>}
    </div>
  );
}
