/**
 * @name 自营业务台账
 */
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, Trash2 } from 'lucide-react';
import {
  AnnotationViewer,
  type AnnotationDirectoryRouteNode,
  type AnnotationSourceDocument,
  type AnnotationViewerOptions,
} from '@axhub/annotation';
import seedRows from './data/rows.json';
import { FilterPanel } from './components/FilterPanel';
import { LedgerKpiRow } from './components/LedgerKpiRow';
import { SelfLedgerTable } from './components/SelfLedgerTable';
import { TablePagination } from '../vehicle-management/components/TablePagination';
import {
  EMPTY_SELF_FILTERS,
  type SelfOperatedFilters,
  type SelfOperatedLedgerRow,
} from './types';
import { applySelfFilters, sumSelfKpi } from './utils/ledger';
import annotationSourceDocument from './annotation-source.json';

const PAGE_SIZE = 10;

export default function SelfOperatedBusinessLedgerApp() {
  const [records] = 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 [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [toast, setToast] = useState('');

  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 = () => {
    setAppliedFilters(pendingFilters);
    setPage(1);
    setSelectedIds(new Set());
  };

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

  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">
        <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" data-annotation-id="sob-toolbar">
            <div className="vm-table-actions">
              <button type="button" className="vm-btn vm-btn-secondary" onClick={() => showToast('打开批量导入弹窗（原型演示）')}>
                <FileUp size={16} aria-hidden />
                批量导入
              </button>
              <button type="button" className="vm-btn vm-btn-ghost" onClick={() => showToast(`导出 ${filtered.length} 条（原型演示）`)}>
                <Download size={16} aria-hidden />
                导出
              </button>
              <button
                type="button"
                className="vm-btn vm-btn-ghost"
                onClick={() => showToast(`批量删除 ${selectedIds.size} 条（原型演示）`)}
              >
                <Trash2 size={16} aria-hidden />
                批量删除
              </button>
              <button type="button" className="vm-btn vm-btn-primary" onClick={() => showToast('表格底部新增行（原型演示）')}>
                <Plus size={16} aria-hidden />
                添加行
              </button>
            </div>
          </div>

          <div className="vm-table-card">
            <SelfLedgerTable
              records={paged}
              selectedIds={selectedIds}
              onToggleRow={(id, checked) => {
                setSelectedIds((prev) => {
                  const next = new Set(prev);
                  if (checked) next.add(id);
                  else next.delete(id);
                  return next;
                });
              }}
              onToggleAll={(checked) => {
                setSelectedIds(checked ? new Set(paged.map((r) => r.id)) : new Set());
              }}
              onEdit={(row) => showToast(`编辑：${row.plateNo} · ${row.dispatchDate}（原型演示）`)}
              onDelete={(row) => showToast(`删除：${row.plateNo}（原型演示）`)}
            />
            <div className="vm-table-footer ldb-table-footer">
              <span className="ldb-table-total">共 {filtered.length} 条</span>
              <TablePagination
                page={Math.min(page, totalPages)}
                pageSize={pageSize}
                total={filtered.length}
                onPageChange={setPage}
                onPageSizeChange={(size) => { setPageSize(size); setPage(1); }}
              />
            </div>
          </div>
        </section>

        {toast && <div className="vm-toast" role="status">{toast}</div>}
      </div>
      <AnnotationViewer source={annotationSourceDocument as AnnotationSourceDocument} options={annotationOptions} />
    </>
  );
}
