import React, { useCallback, useMemo, useState } from 'react';
import { Table } from 'antd';
import { OperationActions } from '../../../common/OperationActions';
import type { ColumnsType } from 'antd/es/table';
import type { BillCandidate, PaymentRecord } from '../types';
import { calcUnclaimedAmount, formatMoney } from '../utils/payment';
import { LinkedBillsNestedTable } from './LinkedBillsNestedTable';

const ONEOS_ANT_TABLE_GLOBAL_FIX = [
  '.ant-table-container .ant-table-header { margin-bottom: 0 !important; }',
  '.ant-table-container .ant-table-body { margin-top: 0 !important; }',
  '.ant-table-container .ant-table-body > table, .ant-table-content table { margin-top: 0 !important; }',
  '.ant-table-tbody > tr.ant-table-measure-row, .ant-table-tbody > tr.ant-table-measure-row > td, .ant-table-tbody > tr.ant-table-measure-row > th { display: none !important; height: 0 !important; max-height: 0 !important; min-height: 0 !important; padding: 0 !important; margin: 0 !important; border: none !important; line-height: 0 !important; font-size: 0 !important; overflow: hidden !important; visibility: hidden !important; pointer-events: none !important; }',
  '.vm-page.lc-page.pr-page .vm-list-table .ant-table-tbody > tr.ant-table-expanded-row > td { padding: 8px 120px 12px 8px !important; overflow: visible !important; }',
  '.vm-list-table .ant-table-thead th,.vm-list-table .ant-table-tbody td{white-space:nowrap;}',
].join('\n');

interface PaymentRecordsTableProps {
  records: PaymentRecord[];
  billPool: BillCandidate[];
  loading?: boolean;
  onLinkBills: (record: PaymentRecord) => void;
}

export function PaymentRecordsTable({
  records,
  billPool,
  loading = false,
  onLinkBills,
}: PaymentRecordsTableProps) {
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);

  const toggleRowExpand = useCallback((recordId: string) => {
    setExpandedRowKeys((prev) => (
      prev.includes(recordId)
        ? prev.filter((key) => key !== recordId)
        : [...prev, recordId]
    ));
  }, []);

  const columns = useMemo<ColumnsType<PaymentRecord>>(() => [
    {
      title: '收款时间',
      dataIndex: 'paymentTime',
      key: 'paymentTime',
      width: 168,
      className: 'tabular-nums',
      render: (value: string) => value || '—',
    },
    {
      title: '汇款账户名',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 200,
      ellipsis: true,
      render: (value: string) => value || '—',
    },
    {
      title: '公司主体',
      dataIndex: 'companyEntity',
      key: 'companyEntity',
      width: 240,
      ellipsis: true,
      render: (value: string) => value || '—',
    },
    {
      title: '银行',
      dataIndex: 'bank',
      key: 'bank',
      width: 180,
      ellipsis: true,
      render: (value: string) => value || '—',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      className: 'tabular-nums ldb-col-money',
      render: (value: number) => formatMoney(value),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 160,
      ellipsis: true,
      className: 'pr-col-remark',
      render: (value: string) => value || '—',
    },
    {
      title: '关联账单',
      key: 'linkedBills',
      width: 96,
      className: 'pr-linked-col',
      render: (_, row) => {
        const count = row.linkedBills?.length ?? 0;
        if (count === 0) {
          return <span className="pr-linked-empty">未关联</span>;
        }
        const expanded = expandedRowKeys.includes(row.id);
        return (
          <button
            type="button"
            className="pr-linked-count-btn"
            aria-expanded={expanded}
            onClick={() => toggleRowExpand(row.id)}
          >
            {count} 条
          </button>
        );
      },
    },
    {
      title: '未关联金额',
      key: 'unlinked',
      width: 120,
      className: 'tabular-nums ldb-col-money',
      render: (_, row) => {
        const unlinked = calcUnclaimedAmount(row);
        return (
          <span className={unlinked > 0 ? 'pr-unlinked--pending' : undefined}>
            {formatMoney(unlinked)}
          </span>
        );
      },
    },
    {
      title: '操作人',
      dataIndex: 'operatorName',
      key: 'operatorName',
      width: 100,
      render: (value: string) => value || '—',
    },
    {
      title: '操作时间',
      dataIndex: 'operatedAt',
      key: 'operatedAt',
      width: 168,
      className: 'tabular-nums',
      render: (value: string) => value || '—',
    },
    {
      title: '操作',
      key: 'action',
      width: 168,
      fixed: 'right',
      render: (_, row) => (
        <OperationActions
          more={[
            {
              key: 'linkBills',
              label: '关联账单',
              onClick: () => onLinkBills(row),
            },
          ]}
        />
      ),
    },
  ], [billPool, expandedRowKeys, onLinkBills, toggleRowExpand]);

  const scrollX = columns.reduce((sum, col) => sum + (Number(col.width) || 0), 0) + 48;

  return (
    <>
      <style>{ONEOS_ANT_TABLE_GLOBAL_FIX}</style>
      <div className="vm-table-wrap" data-annotation-id="pr-table">
        <Table<PaymentRecord>
          className="vm-list-table pr-list-table lc-list-table--nested"
          rowKey="id"
          columns={columns}
          dataSource={records}
          loading={loading}
          tableLayout="fixed"
          scroll={{ x: scrollX, y: 'calc(100vh - 560px)' }}
          size="small"
          pagination={false}
          expandable={{
            columnWidth: 48,
            expandedRowKeys,
            onExpandedRowsChange: (keys) => setExpandedRowKeys(keys),
            expandedRowRender: (record) => (
              <LinkedBillsNestedTable
                linkedBills={record.linkedBills}
                billPool={billPool}
                paymentCustomerName={record.customerName}
              />
            ),
            rowExpandable: (record) => (record.linkedBills?.length ?? 0) > 0,
          }}
          locale={{
            emptyText: (
              <div className="vm-table-empty" role="status">
                <p>暂无收款记录</p>
                <p className="vm-table-empty__hint">可点击「新增收款」录入，或通过批量导入上传 Excel。</p>
              </div>
            ),
          }}
        />
      </div>
    </>
  );
}
