/**
 * @name 物流业务明细
 * 设计规范：ledger-shared/DESIGN.md · vm-page + ldb-page（与租赁业务明细、租赁合同列表对齐）
 */
import '../vehicle-management/style.css';
import '../lease-business-ledger/styles/index.css';
import './styles/index.css';
import React, { useCallback, useMemo, useState } from 'react';
import { Download, FileUp, Plus } from 'lucide-react';
import {
  type AnnotationDirectoryRouteNode,
  type AnnotationSourceDocument,
  type AnnotationViewerOptions
} from '@axhub/annotation';
import { PrototypeAnnotationHost } from '../../common/prototype-annotation-host';
import seedRows from './data/rows.json';
import { FilterPanel } from './components/FilterPanel';
import { LedgerKpiRow } from './components/LedgerKpiRow';
import { SelfLedgerTable } from './components/SelfLedgerTable';
import { SelfImportModal } from './components/SelfImportModal';
import { TablePagination } from '../vehicle-management/components/TablePagination';
import { DeleteConfirmModal } from '../lease-business-ledger/components/DeleteConfirmModal';
import {
  EMPTY_SELF_FILTERS,
  type SelfOperatedFilters,
  type SelfOperatedLedgerRow,
} from './types';
import { applySelfFilters, sumSelfKpi } from './utils/ledger';
import {
  downloadSelfImportErrorLog,
  downloadSelfImportTemplate,
  parseSelfImportFile,
  type SelfImportErrorRow,
} from './utils/batch-io';
import annotationSourceDocument from './annotation-source.json';

const PAGE_SIZE = 10;

export default function SelfOperatedBusinessLedgerApp() {
  const [records, setRecords] = useState<SelfOperatedLedgerRow[]>(seedRows as SelfOperatedLedgerRow[]);
  const [pendingFilters, setPendingFilters] = useState<SelfOperatedFilters>(EMPTY_SELF_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<SelfOperatedFilters>(EMPTY_SELF_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  const [toast, setToast] = useState('');
  const [tableLoading, setTableLoading] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<SelfOperatedLedgerRow | null>(null);
  const [importOpen, setImportOpen] = useState(false);
  const [importErrors, setImportErrors] = useState<SelfImportErrorRow[]>([]);
  const [importErrorHeaders, setImportErrorHeaders] = useState<string[]>([]);

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

  const filtered = useMemo(() => applySelfFilters(records, appliedFilters), [records, appliedFilters]);
  const kpi = useMemo(() => sumSelfKpi(filtered), [filtered]);
  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 handleSearch = () => {
    setTableLoading(true);
    window.setTimeout(() => {
      setAppliedFilters(pendingFilters);
      setPage(1);
      setTableLoading(false);
    }, 320);
  };

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

  const handleImport = async (file: File) => {
    try {
      const result = await parseSelfImportFile(file);
      setImportErrors(result.errors);
      setImportErrorHeaders(result.fileHeaders);

      if (result.success.length === 0 && result.errors.length === 0) {
        showToast('未解析到有效数据，请检查模板与表头');
        return;
      }

      if (result.success.length > 0) {
        setRecords((prev) => [...result.success, ...prev]);
        setPage(1);
      }

      if (result.errors.length > 0 && result.success.length > 0) {
        showToast(`已导入 ${result.success.length} 条；${result.errors.length} 条失败，可下载错误日志`);
      } else if (result.errors.length > 0) {
        showToast(`${result.errors.length} 条导入失败，请下载错误日志查看原因`);
      } else {
        setImportOpen(false);
        showToast(`已导入 ${result.success.length} 条明细，金额/总成本/盈亏已自动计算`);
      }
    } catch {
      showToast('导入失败，请检查文件格式');
    }
  };

  const annotationOptions = useMemo<AnnotationViewerOptions>(
    () => ({
      showToolbar: true,
      showThemeToggle: true,
      showColorFilter: true,
      emptyWhenNoData: false,
      toolbarEdge: 'right',
      currentPageId: 'list',
      onDirectoryRoute: (_node: AnnotationDirectoryRouteNode) => {},
    }),
    [],
  );

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

        <LedgerKpiRow summary={kpi} />

        <section className="vm-table-section">
          <div className="vm-table-toolbar ldb-table-toolbar" data-annotation-id="sob-toolbar">
            <div className="vm-table-actions">
              <button
                type="button"
                className="vm-btn vm-btn-secondary ldb-toolbar-btn"
                data-vm-icon="import"
                onClick={() => {
                  setImportErrors([]);
                  setImportErrorHeaders([]);
                  setImportOpen(true);
                }}
              >
                批量导入
              </button>
              <button type="button" className="vm-btn vm-btn-ghost ldb-toolbar-btn" data-vm-icon="download" onClick={() => showToast(`导出 ${filtered.length} 条（原型演示）`)}>
                导出
              </button>
            </div>
          </div>

          <div className="vm-table-card">
            <SelfLedgerTable
              records={paged}
              loading={tableLoading}
              onEdit={(row) => showToast(`编辑：${row.plateNo} · ${row.dispatchDate}（原型演示）`)}
              onDelete={(row) => setDeleteTarget(row)}
            />
            <div className="vm-table-footer ldb-table-footer">
              <div className="ldb-table-footer-actions">
                <TablePagination
                  page={Math.min(page, totalPages)}
                  pageSize={pageSize}
                  total={filtered.length}
                  onPageChange={setPage}
                  onPageSizeChange={(size) => { setPageSize(size); setPage(1); }}
                />
                <button
                  type="button"
                  className="vm-btn vm-btn-secondary ldb-toolbar-btn"
                  data-annotation-id="sob-btn-add-row"
                  data-vm-icon="plus"
                  onClick={() => showToast('表格底部新增行（原型演示）')}
                >
                  添加行
                </button>
              </div>
            </div>
          </div>
        </section>

        {toast && <div className="vm-toast" role="status">{toast}</div>}
      </div>

      <DeleteConfirmModal
        open={Boolean(deleteTarget)}
        plateNo={deleteTarget?.plateNo ?? ''}
        onCancel={() => setDeleteTarget(null)}
        onConfirm={() => {
          if (!deleteTarget) return;
          setRecords((prev) => prev.filter((row) => row.id !== deleteTarget.id));
          setDeleteTarget(null);
          showToast(`已删除 ${deleteTarget.plateNo}（原型）`);
        }}
      />

      <SelfImportModal
        open={importOpen}
        onClose={() => setImportOpen(false)}
        onDownloadTemplate={downloadSelfImportTemplate}
        onImport={handleImport}
        failedCount={importErrors.length}
        onDownloadErrorLog={
          importErrors.length > 0
            ? () => downloadSelfImportErrorLog(importErrors, importErrorHeaders)
            : undefined
        }
      />

      <PrototypeAnnotationHost source={annotationSourceDocument as AnnotationSourceDocument} options={annotationOptions} />
    </>
  );
}
