import React, { useEffect, useMemo, useState } from 'react';
import { Modal, Table, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  LN_MODAL_DETAIL_TABLE_CLASS,
  sumColumnScrollX,
  warnMissingModalColumnWidths,
} from '../../../common/modalDetailTable';
import type { PaymentRecord } from '../types';
import { EMPTY_PAYMENT_KPI_DETAIL_FILTERS } from '../types';
import {
  buildDetailCustomerOptions,
  buildLinkedDetailRows,
  buildReceivedDetailRows,
  buildUnlinkedDetailRows,
  exportKpiDetailCsv,
  filterLinkedDetailRows,
  filterReceivedDetailRows,
  filterUnlinkedDetailRows,
  formatMoney,
  sumLinkedDetailAmount,
  sumReceivedDetailAmount,
  sumUnlinkedDetailAmount,
  type PaymentKpiKey,
  type PaymentLinkedDetailRow,
  type PaymentReceivedDetailRow,
  type PaymentUnlinkedDetailRow,
} from '../utils/payment';
import { PaymentKpiDetailFilterBar } from './PaymentKpiDetailFilterBar';

interface KpiModalMeta {
  title: string;
  amountLabel: string;
  width: number;
  subtitle: string;
  tone: 'received' | 'linked' | 'unlinked';
}

const KPI_MODAL_META: Record<PaymentKpiKey, KpiModalMeta> = {
  received: {
    title: '到账总金额明细',
    amountLabel: '到账金额合计',
    width: 800,
    subtitle: '当前筛选范围内全部收款记录的到账明细',
    tone: 'received',
  },
  linked: {
    title: '认领总金额明细',
    amountLabel: '认领金额合计',
    width: 860,
    subtitle: '按收款记录汇总已认领金额（到账金额中已关联账单的部分）',
    tone: 'linked',
  },
  unlinked: {
    title: '未关联总金额明细',
    amountLabel: '未关联金额合计',
    width: 900,
    subtitle: '到账金额减去已认领金额后，尚未关联的部分',
    tone: 'unlinked',
  },
};

function KpiModalIcon({ tone }: { tone: KpiModalMeta['tone'] }) {
  if (tone === 'linked') {
    return (
      <svg xmlns="http://www.w3.org/2000/svg" width={22} height={22} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
        <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
        <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
      </svg>
    );
  }
  if (tone === 'unlinked') {
    return (
      <svg xmlns="http://www.w3.org/2000/svg" width={22} height={22} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
        <circle cx="12" cy="12" r="10" />
        <path d="M12 8v4" />
        <path d="M12 16h.01" />
      </svg>
    );
  }
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={22} height={22} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
      <path d="M12 2v20" />
      <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
    </svg>
  );
}

function ExportIcon() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={14} height={14} 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>
  );
}

const RECEIVED_COLUMNS: ColumnsType<PaymentReceivedDetailRow> = [
  { title: '收款时间', dataIndex: 'paymentTime', key: 'paymentTime', width: 156, fixed: 'left', className: 'tabular-nums ln-modal-detail-table__sticky-time' },
  { title: '客户名称', dataIndex: 'customerName', key: 'customerName', width: 220, ellipsis: true },
  { title: '到账金额', dataIndex: 'amount', key: 'amount', width: 112, align: 'left', className: 'tabular-nums ln-modal-detail-table__money', render: formatMoney },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 172, ellipsis: true },
];

const LINKED_COLUMNS: ColumnsType<PaymentLinkedDetailRow> = [
  { title: '收款时间', dataIndex: 'paymentTime', key: 'paymentTime', width: 156, fixed: 'left', className: 'tabular-nums ln-modal-detail-table__sticky-time' },
  { title: '客户名称', dataIndex: 'customerName', key: 'customerName', width: 200, ellipsis: true },
  { title: '到账金额', dataIndex: 'amount', key: 'amount', width: 112, align: 'left', className: 'tabular-nums ln-modal-detail-table__money', render: formatMoney },
  { title: '认领金额', dataIndex: 'linkedAmount', key: 'linkedAmount', width: 112, align: 'left', className: 'tabular-nums ln-modal-detail-table__money', render: formatMoney },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 160, ellipsis: true },
];

const UNLINKED_COLUMNS: ColumnsType<PaymentUnlinkedDetailRow> = [
  { title: '收款时间', dataIndex: 'paymentTime', key: 'paymentTime', width: 148, fixed: 'left', className: 'tabular-nums ln-modal-detail-table__sticky-time' },
  { title: '客户名称', dataIndex: 'customerName', key: 'customerName', width: 168, ellipsis: true },
  { title: '到账金额', dataIndex: 'amount', key: 'amount', width: 100, align: 'left', className: 'tabular-nums ln-modal-detail-table__money', render: formatMoney },
  { title: '已认领', dataIndex: 'linkedAmount', key: 'linkedAmount', width: 100, align: 'left', className: 'tabular-nums ln-modal-detail-table__money', render: formatMoney },
  { title: '未关联金额', dataIndex: 'unlinkedAmount', key: 'unlinkedAmount', width: 112, align: 'left', className: 'tabular-nums ln-modal-detail-table__money', render: (v: number) => (
    <span className={v > 0 ? 'pr-unlinked--pending' : undefined}>{formatMoney(v)}</span>
  ) },
  { title: '备注', dataIndex: 'remark', key: 'remark', width: 140, ellipsis: true },
];

warnMissingModalColumnWidths(RECEIVED_COLUMNS, 'PaymentKpiDetailModal.received');
warnMissingModalColumnWidths(LINKED_COLUMNS, 'PaymentKpiDetailModal.linked');
warnMissingModalColumnWidths(UNLINKED_COLUMNS, 'PaymentKpiDetailModal.unlinked');

interface PaymentKpiDetailModalProps {
  open: boolean;
  kpiKey: PaymentKpiKey | null;
  records: PaymentRecord[];
  onClose: () => void;
}

function ModalTitle({ meta }: { meta: KpiModalMeta }) {
  return (
    <div className="pr-kpi-detail-modal__title">
      <span className={`pr-kpi-detail-modal__icon pr-kpi-detail-modal__icon--${meta.tone}`} aria-hidden>
        <KpiModalIcon tone={meta.tone} />
      </span>
      <span className="pr-kpi-detail-modal__title-text">
        <span className="pr-kpi-detail-modal__title-main">{meta.title}</span>
        <span className="pr-kpi-detail-modal__title-sub">{meta.subtitle}</span>
      </span>
    </div>
  );
}

function EmptyDetail({ text }: { text: string }) {
  return (
    <div className="ln-modal-detail-empty" role="status">
      <p>{text}</p>
      <p className="ln-modal-detail-empty__hint">可调整筛选条件后重新查询</p>
    </div>
  );
}

export function PaymentKpiDetailModal({
  open,
  kpiKey,
  records,
  onClose,
}: PaymentKpiDetailModalProps) {
  const meta = kpiKey ? KPI_MODAL_META[kpiKey] : null;
  const [pendingFilters, setPendingFilters] = useState(EMPTY_PAYMENT_KPI_DETAIL_FILTERS);
  const [appliedFilters, setAppliedFilters] = useState(EMPTY_PAYMENT_KPI_DETAIL_FILTERS);

  useEffect(() => {
    if (open) {
      setPendingFilters(EMPTY_PAYMENT_KPI_DETAIL_FILTERS);
      setAppliedFilters(EMPTY_PAYMENT_KPI_DETAIL_FILTERS);
    }
  }, [open, kpiKey]);

  const allReceivedRows = useMemo(
    () => (kpiKey === 'received' ? buildReceivedDetailRows(records) : []),
    [kpiKey, records],
  );
  const allLinkedRows = useMemo(
    () => (kpiKey === 'linked' ? buildLinkedDetailRows(records) : []),
    [kpiKey, records],
  );
  const allUnlinkedRows = useMemo(
    () => (kpiKey === 'unlinked' ? buildUnlinkedDetailRows(records) : []),
    [kpiKey, records],
  );

  const receivedRows = useMemo(
    () => filterReceivedDetailRows(allReceivedRows, appliedFilters),
    [allReceivedRows, appliedFilters],
  );
  const linkedRows = useMemo(
    () => filterLinkedDetailRows(allLinkedRows, appliedFilters),
    [allLinkedRows, appliedFilters],
  );
  const unlinkedRows = useMemo(
    () => filterUnlinkedDetailRows(allUnlinkedRows, appliedFilters),
    [allUnlinkedRows, appliedFilters],
  );

  const customerOptions = useMemo(() => {
    if (kpiKey === 'received') {
      return buildDetailCustomerOptions(allReceivedRows.map((row) => row.customerName));
    }
    if (kpiKey === 'linked') {
      return buildDetailCustomerOptions(allLinkedRows.map((row) => row.customerName));
    }
    if (kpiKey === 'unlinked') {
      return buildDetailCustomerOptions(allUnlinkedRows.map((row) => row.customerName));
    }
    return [];
  }, [kpiKey, allReceivedRows, allLinkedRows, allUnlinkedRows]);

  const rowCount = kpiKey === 'received'
    ? receivedRows.length
    : kpiKey === 'linked'
      ? linkedRows.length
      : unlinkedRows.length;

  const filteredTotalAmount = kpiKey === 'received'
    ? sumReceivedDetailAmount(receivedRows)
    : kpiKey === 'linked'
      ? sumLinkedDetailAmount(linkedRows)
      : sumUnlinkedDetailAmount(unlinkedRows);

  const tableProps = {
    className: LN_MODAL_DETAIL_TABLE_CLASS,
    rowKey: 'key' as const,
    size: 'small' as const,
    tableLayout: 'fixed' as const,
    pagination: {
      pageSize: 8,
      showSizeChanger: false,
      hideOnSinglePage: true,
      showTotal: (total: number) => `共 ${total} 条`,
    },
    scroll: { y: 320 },
  };

  const amountToneClass = meta?.tone === 'linked'
    ? 'pr-kpi-detail-modal__stat-val--linked'
    : meta?.tone === 'unlinked'
      ? 'pr-kpi-detail-modal__stat-val--warn'
      : '';

  const handleExport = () => {
    if (!kpiKey) return;
    const count = exportKpiDetailCsv(kpiKey, receivedRows, linkedRows, unlinkedRows);
    message.success(`已导出 ${count} 条明细（原型演示）`);
  };

  return (
    <Modal
      className={`pr-kpi-detail-modal pr-kpi-detail-modal--${meta?.tone ?? 'received'}`}
      title={meta ? <ModalTitle meta={meta} /> : null}
      open={open}
      onCancel={onClose}
      centered
      width={meta?.width ?? 800}
      destroyOnClose
      maskClosable
      footer={null}
    >
      <div className="pr-kpi-detail-modal__body">
        {kpiKey && (
          <PaymentKpiDetailFilterBar
            kpiKey={kpiKey}
            filters={pendingFilters}
            customerOptions={customerOptions}
            onChange={(patch) => setPendingFilters((prev) => ({ ...prev, ...patch }))}
            onReset={() => {
              setPendingFilters(EMPTY_PAYMENT_KPI_DETAIL_FILTERS);
              setAppliedFilters(EMPTY_PAYMENT_KPI_DETAIL_FILTERS);
            }}
            onSearch={() => setAppliedFilters(pendingFilters)}
          />
        )}

        <div className="pr-kpi-detail-modal__stats" role="group" aria-label="汇总统计">
          <div className={`pr-kpi-detail-modal__stat-card pr-kpi-detail-modal__stat-card--primary pr-kpi-detail-modal__stat-card--${meta?.tone ?? 'received'}`}>
            <span className="pr-kpi-detail-modal__stat-label">{meta?.amountLabel}</span>
            <strong className={`pr-kpi-detail-modal__stat-val tabular-nums ${amountToneClass}`}>
              {formatMoney(filteredTotalAmount)}
            </strong>
          </div>
          <div className="pr-kpi-detail-modal__stat-card">
            <span className="pr-kpi-detail-modal__stat-label">明细条数</span>
            <strong className="pr-kpi-detail-modal__stat-val tabular-nums">{rowCount}</strong>
          </div>
        </div>

        <section className="ln-modal-detail-panel" aria-label="明细列表">
          <header className="ln-modal-detail-panel__head pr-kpi-detail-panel__head">
            <span className="ln-modal-detail-panel__title">明细列表</span>
            <div className="pr-kpi-detail-panel__head-actions">
              <span className="ln-modal-detail-panel__meta tabular-nums">{rowCount} 条记录</span>
              <button
                type="button"
                className="vm-btn vm-btn-ghost vm-btn-sm pr-kpi-detail-panel__export"
                data-vm-icon="download"
                onClick={handleExport}
                disabled={rowCount === 0}
              >
                导出
              </button>
            </div>
          </header>

          {kpiKey === 'received' && (
            <Table<PaymentReceivedDetailRow>
              {...tableProps}
              columns={RECEIVED_COLUMNS}
              dataSource={receivedRows}
              scroll={{ ...tableProps.scroll, x: sumColumnScrollX(RECEIVED_COLUMNS) }}
              locale={{ emptyText: <EmptyDetail text="当前筛选条件下暂无收款记录" /> }}
            />
          )}

          {kpiKey === 'linked' && (
            <Table<PaymentLinkedDetailRow>
              {...tableProps}
              columns={LINKED_COLUMNS}
              dataSource={linkedRows}
              scroll={{ ...tableProps.scroll, x: sumColumnScrollX(LINKED_COLUMNS) }}
              locale={{ emptyText: <EmptyDetail text="当前筛选条件下暂无已认领收款记录" /> }}
            />
          )}

          {kpiKey === 'unlinked' && (
            <Table<PaymentUnlinkedDetailRow>
              {...tableProps}
              columns={UNLINKED_COLUMNS}
              dataSource={unlinkedRows}
              scroll={{ ...tableProps.scroll, x: sumColumnScrollX(UNLINKED_COLUMNS) }}
              locale={{ emptyText: <EmptyDetail text="当前筛选条件下暂无未关联收款记录" /> }}
            />
          )}
        </section>
      </div>
    </Modal>
  );
}
