import React, { useMemo, useState } from 'react';
import { X } from 'lucide-react';
import type { LeaseLedgerRow, ReceiptRecord } from '../types';
import { calcUnreceived, formatMoney } from '../utils/ledger';

interface ReceiptLinkModalProps {
  open: boolean;
  record: LeaseLedgerRow | null;
  receipts: ReceiptRecord[];
  onClose: () => void;
  onConfirm: (recordId: string, selectedIds: string[], linkedAmount: number, allocations: Record<string, number>) => void;
}

export function ReceiptLinkModal({
  open,
  record,
  receipts,
  onClose,
  onConfirm,
}: ReceiptLinkModalProps) {
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [allocations, setAllocations] = useState<Record<string, number>>({});

  const filteredReceipts = useMemo(() => {
    if (!record) return [];
    return receipts.filter((item) => item.customerName === record.customerName);
  }, [record, receipts]);

  const linkedAmount = useMemo(
    () => Object.values(allocations).reduce((sum, v) => sum + v, 0),
    [allocations],
  );

  if (!open || !record) return null;

  const toggle = (id: string, amount: number) => {
    if (selected.has(id)) {
      setSelected((prev) => {
        const next = new Set(prev);
        next.delete(id);
        return next;
      });
      setAllocations((prev) => {
        const copy = { ...prev };
        delete copy[id];
        return copy;
      });
      return;
    }
    setSelected((prev) => new Set(prev).add(id));
    setAllocations((prev) => {
      const used = Object.values(prev).reduce((sum, v) => sum + v, 0);
      const remaining = Math.max(0, record.receivableTotal - used);
      return { ...prev, [id]: Math.min(amount, remaining) };
    });
  };

  const updateAllocation = (id: string, value: number, max: number) => {
    setAllocations((prev) => ({ ...prev, [id]: Math.min(Math.max(0, value), max) }));
  };

  const handleConfirm = () => {
    if (selected.size === 0) return;
    onConfirm(record.id, Array.from(selected), linkedAmount, allocations);
    setSelected(new Set());
    setAllocations({});
  };

  const unreceived = calcUnreceived(record);
  const overflow = Math.max(0, Math.round((linkedAmount - record.receivableTotal) * 100) / 100);
  const previewStatus = linkedAmount >= record.receivableTotal
    ? '已收款'
    : linkedAmount > 0
      ? '部分收款'
      : '已确认';

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal ldb-receipt-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="receipt-link-title"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="vm-modal-header">
          <h2 id="receipt-link-title" className="vm-modal-title">关联收款记录</h2>
          <button type="button" className="vm-modal-close" onClick={onClose} aria-label="关闭">
            <X size={18} aria-hidden />
          </button>
        </header>
        <div className="vm-modal-body">
          <div className="ldb-receipt-summary">
            <span>应收合计 <strong className="tabular-nums">{formatMoney(record.receivableTotal)}</strong></span>
            <span>当前未收 <strong className="tabular-nums">{formatMoney(unreceived)}</strong></span>
            <span>计入本账单 <strong className="tabular-nums">{formatMoney(Math.min(linkedAmount, record.receivableTotal))}</strong></span>
            <span>预计状态 <strong>{previewStatus}</strong></span>
          </div>
          {overflow > 0 && (
            <p className="ldb-overflow-hint">
              收款合计超出应收 {formatMoney(overflow)}，多出部分显示在对应收款单据下，请自行分配计入金额。
            </p>
          )}
          <div className="ldb-receipt-table-wrap">
            <table className="vm-table ldb-receipt-table">
              <thead>
                <tr>
                  <th className="ldb-col-check" aria-label="选择" />
                  <th>到账时间</th>
                  <th>客户名称</th>
                  <th className="ldb-col-money">到账金额</th>
                  <th className="ldb-col-money">计入本账单</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                {filteredReceipts.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="ldb-receipt-empty">暂无匹配的到账记录</td>
                  </tr>
                ) : filteredReceipts.map((item) => {
                  const checked = selected.has(item.id);
                  const alloc = allocations[item.id] ?? 0;
                  const overflowAmt = checked ? Math.max(0, item.amount - alloc) : 0;
                  return (
                    <tr key={item.id}>
                      <td className="ldb-col-check">
                        <input
                          type="checkbox"
                          checked={checked}
                          onChange={() => toggle(item.id, item.amount)}
                          aria-label={`选择到账记录 ${item.arrivalTime}`}
                        />
                      </td>
                      <td className="tabular-nums">{item.arrivalTime}</td>
                      <td>{item.customerName}</td>
                      <td className="ldb-col-money tabular-nums">{formatMoney(item.amount)}</td>
                      <td className="ldb-col-money">
                        {checked ? (
                          <input
                            type="number"
                            className="vm-input ldb-alloc-input tabular-nums"
                            value={alloc || ''}
                            min={0}
                            max={item.amount}
                            step={0.01}
                            aria-label={`${item.arrivalTime} 计入金额`}
                            onChange={(e) => updateAllocation(item.id, Number(e.target.value) || 0, item.amount)}
                          />
                        ) : '—'}
                      </td>
                      <td>
                        {item.remark}
                        {overflowAmt > 0 && (
                          <span className="ldb-overflow-tag">余 {formatMoney(overflowAmt)} 待分配</span>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-ghost" onClick={onClose}>取消</button>
          <button type="button" className="vm-btn vm-btn-primary" disabled={selected.size === 0} onClick={handleConfirm}>
            确认关联
          </button>
        </footer>
      </div>
    </div>
  );
}
