/**
 * @name 收款记录
 * 设计规范：oneos-app.css · vm-page lc-page（对齐租赁合同管理）
 */
import 'antd/dist/reset.css';
import '../vehicle-management/style.css';
import './styles/index.css';
import React, { useMemo, useState } from 'react';
import { App, ConfigProvider, message } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import {
  type AnnotationDirectoryRouteNode,
  type AnnotationSourceDocument,
  type AnnotationViewerOptions
} from '@axhub/annotation';
import { PrototypeAnnotationHost } from '../../common/prototype-annotation-host';
import seedRecords from './data/records.json';
import seedBills from './data/bills.json';
import { FilterPanel } from './components/FilterPanel';
import { PaymentRecordsTable } from './components/PaymentRecordsTable';
import { AddPaymentModal, type AddPaymentFormValues } from './components/AddPaymentModal';
import { BillLinkModal } from './components/BillLinkModal';
import { PaymentKpiDetailModal } from './components/PaymentKpiDetailModal';
import { TablePagination } from '../vehicle-management/components/TablePagination';
import type { BillCandidate, LinkedBill, PaymentRecord, PaymentRecordFilters } from './types';
import { EMPTY_PAYMENT_FILTERS } from './types';
import {
  applyPaymentFilters,
  flattenBillPool,
  formatMoney,
  sumLinkedAmount,
  sumPaymentAmount,
  sumUnclaimedAmount,
  type PaymentKpiKey,
} from './utils/payment';
import annotationSourceDocument from './annotation-source.json';

const PAGE_SIZE = 10;
const OPERATOR_NAME = '张专员';

dayjs.locale('zh-cn');

const vmTheme = {
  token: {
    colorPrimary: '#32a06e',
    colorLink: '#32a06e',
    colorLinkHover: '#3fb87c',
    borderRadius: 8,
    fontFamily:
      'Inter, -apple-system, BlinkMacSystemFont, "SF Pro Display", "PingFang SC", "Microsoft YaHei", sans-serif',
    fontSize: 14,
    colorText: '#18181b',
    colorTextSecondary: '#52525b',
    colorBorder: '#e5e7eb',
    colorBgContainer: '#ffffff',
  },
  components: {
    Table: {
      headerBg: '#f6f7f7',
      headerColor: '#71717a',
      rowHoverBg: '#f6f7f7',
      borderColor: '#e5e7eb',
      cellPaddingBlock: 8,
      cellPaddingInline: 12,
    },
    Card: {
      borderRadiusLG: 12,
    },
    InputNumber: {
      handleVisible: true,
    },
  },
};

const AMOUNT_KPI_CARDS = [
  { key: 'received', title: '到账总金额', desc: '当前筛选范围内全部收款记录的到账金额合计' },
  { key: 'linked', title: '认领总金额', desc: '当前筛选范围内收款记录已认领金额合计' },
  { key: 'unlinked', title: '未关联总金额', desc: '当前筛选范围内收款记录未关联金额合计（到账金额 − 已认领金额）' },
] as const;

function ExportIcon() {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width={16}
      height={16}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="7 10 12 15 17 10" />
      <line x1="12" x2="12" y1="15" y2="3" />
    </svg>
  );
}

function ImportIcon() {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width={16}
      height={16}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="17 8 12 3 7 8" />
      <line x1="12" x2="12" y1="3" y2="15" />
    </svg>
  );
}

function PaymentRecordsContent() {
  const [records, setRecords] = useState<PaymentRecord[]>(seedRecords as PaymentRecord[]);
  const [pendingFilters, setPendingFilters] = useState<PaymentRecordFilters>(EMPTY_PAYMENT_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState<PaymentRecordFilters>(EMPTY_PAYMENT_FILTERS);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(PAGE_SIZE);
  const [tableLoading, setTableLoading] = useState(false);
  const [addOpen, setAddOpen] = useState(false);
  const [linkRow, setLinkRow] = useState<PaymentRecord | null>(null);
  const [kpiDetailKey, setKpiDetailKey] = useState<PaymentKpiKey | null>(null);

  const billPool = useMemo(
    () => flattenBillPool(seedBills as Record<string, BillCandidate[]>),
    [],
  );

  const filtered = useMemo(
    () => applyPaymentFilters(records, appliedFilters, billPool),
    [records, appliedFilters, billPool],
  );

  const amountKpis = useMemo(() => ({
    received: sumPaymentAmount(filtered),
    linked: sumLinkedAmount(filtered),
    unlinked: sumUnclaimedAmount(filtered),
  }), [filtered]);

  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);
    }, 280);
  };

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

  const handleAdd = (values: AddPaymentFormValues) => {
    const now = new Date();
    const operatedAt = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    const row: PaymentRecord = {
      id: `pr-${Date.now()}`,
      paymentTime: values.paymentTime.length === 16 ? `${values.paymentTime}:00` : values.paymentTime,
      customerName: values.customerName,
      companyEntity: values.companyEntity,
      bank: values.bank,
      amount: values.amount,
      remark: values.remark,
      linkedBills: [],
      operatorName: OPERATOR_NAME,
      operatedAt,
    };
    setRecords((prev) => [row, ...prev]);
    setAddOpen(false);
    message.success('收款记录已新增（原型演示）');
  };

  const handleLinkBills = (recordId: string, linkedBills: LinkedBill[]) => {
    const operatedAt = new Date().toLocaleString('zh-CN', { hour12: false }).replace(/\//g, '-');
    setRecords((prev) => prev.map((row) => (
      row.id === recordId
        ? { ...row, linkedBills, operatedAt, operatorName: OPERATOR_NAME }
        : row
    )));
    setLinkRow(null);
    message.success('账单关联成功（原型演示）');
  };

  const resolveAmountKpiValue = (key: typeof AMOUNT_KPI_CARDS[number]['key']) => {
    if (key === 'received') return formatMoney(amountKpis.received);
    if (key === 'linked') return formatMoney(amountKpis.linked);
    return formatMoney(amountKpis.unlinked);
  };

  const resolveAmountKpiClass = (key: typeof AMOUNT_KPI_CARDS[number]['key']) => {
    if (key === 'linked') return 'pr-kpi-val--linked';
    if (key === 'unlinked') return 'pr-kpi-val--warn';
    return '';
  };

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

      <div className="vm-kpi-row" role="group" aria-label="收款金额统计" data-annotation-id="pr-kpi">
        {AMOUNT_KPI_CARDS.map((card) => (
          <button
            key={card.key}
            type="button"
            className={`vm-kpi-card pr-kpi-card pr-kpi-card--clickable${kpiDetailKey === card.key ? ' pr-kpi-card--active' : ''}`}
            title={`${card.desc}，点击查看明细`}
            aria-label={`${card.title} ${resolveAmountKpiValue(card.key)}，点击查看明细`}
            onClick={() => setKpiDetailKey(card.key)}
          >
            <span className="vm-kpi-main">
              <span className="vm-kpi-eyebrow">{card.title}</span>
              <span className={`vm-kpi-val tabular-nums ${resolveAmountKpiClass(card.key)}`}>
                {resolveAmountKpiValue(card.key)}
              </span>
            </span>
          </button>
        ))}
      </div>

      <section className="vm-table-section" data-annotation-id="pr-list">
        <div className="vm-table-toolbar" data-annotation-id="pr-toolbar">
          <div className="vm-table-actions">
            <button
              type="button"
              className="vm-btn vm-btn-ghost ldb-toolbar-btn"
              data-vm-icon="import"
              onClick={() => message.info('批量导入：请下载模板后上传 Excel（原型演示）')}
            >
              批量导入
            </button>
            <button
              type="button"
              className="vm-btn vm-btn-ghost ldb-toolbar-btn"
              data-vm-icon="download"
              onClick={() => message.info(`已导出 ${filtered.length} 条收款记录（原型演示）`)}
            >
              导出
            </button>
            <button
              type="button"
              className="vm-btn vm-btn-primary ldb-toolbar-btn"
              onClick={() => setAddOpen(true)}
              data-vm-icon="plus"
              data-annotation-id="pr-add-btn"
            >
              新增收款
            </button>
          </div>
        </div>

        <div className="vm-table-card">
          <PaymentRecordsTable
            records={paged}
            billPool={billPool}
            loading={tableLoading}
            onLinkBills={setLinkRow}
          />
          <div className="vm-table-footer">
            <TablePagination
              page={page}
              pageSize={pageSize}
              total={filtered.length}
              onPageChange={setPage}
              onPageSizeChange={(size) => {
                setPageSize(size);
                setPage(1);
              }}
            />
          </div>
        </div>
      </section>

      <AddPaymentModal
        open={addOpen}
        records={records}
        onClose={() => setAddOpen(false)}
        onConfirm={handleAdd}
      />

      <BillLinkModal
        open={Boolean(linkRow)}
        record={linkRow}
        billPool={billPool}
        onClose={() => setLinkRow(null)}
        onConfirm={handleLinkBills}
      />

      <PaymentKpiDetailModal
        open={kpiDetailKey != null}
        kpiKey={kpiDetailKey}
        records={filtered}
        onClose={() => setKpiDetailKey(null)}
      />
    </div>
  );
}

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

  return (
    <ConfigProvider theme={vmTheme} locale={zhCN}>
      <App>
        <PaymentRecordsContent />
      </App>
      <PrototypeAnnotationHost
        source={annotationSourceDocument as AnnotationSourceDocument}
        options={annotationOptions}
      />
    </ConfigProvider>
  );
}
