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

interface AccidentLinkModalProps {
  open: boolean;
  record: LeaseLedgerRow | null;
  accidents: AccidentRecord[];
  onClose: () => void;
  onConfirm: (recordId: string, selectedIds: string[], linkedAmount: number) => void;
}

export function AccidentLinkModal({
  open,
  record,
  accidents,
  onClose,
  onConfirm,
}: AccidentLinkModalProps) {
  const [selected, setSelected] = useState<Set<string>>(new Set());

  const filteredAccidents = useMemo(() => {
    if (!record) return [];
    return accidents.filter((item) => item.plateNo === record.plateNo);
  }, [record, accidents]);

  const linkedAmount = useMemo(
    () => filteredAccidents
      .filter((item) => selected.has(item.id))
      .reduce((sum, item) => sum + item.insuranceSurcharge, 0),
    [filteredAccidents, selected],
  );

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

  const toggle = (id: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

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

  return (
    <div className="vm-modal-backdrop" role="presentation" onClick={onClose}>
      <div
        className="vm-modal ldb-receipt-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="accident-link-title"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="vm-modal-header">
          <h2 id="accident-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">
          <p className="ldb-confirm-meta">
            车牌 {record.plateNo} · 关联后自动汇总保险上浮费
          </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>备注</th>
                </tr>
              </thead>
              <tbody>
                {filteredAccidents.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="ldb-receipt-empty">暂无待关联的事故单据</td>
                  </tr>
                ) : filteredAccidents.map((item) => (
                  <tr key={item.id}>
                    <td className="ldb-col-check">
                      <input
                        type="checkbox"
                        className="vm-checkbox"
                        checked={selected.has(item.id)}
                        onChange={() => toggle(item.id)}
                        aria-label={`选择 ${item.accidentNo}`}
                      />
                    </td>
                    <td>{item.accidentNo}</td>
                    <td className="tabular-nums">{item.occurredAt}</td>
                    <td className="ldb-col-money tabular-nums">{formatMoney(item.insuranceSurcharge)}</td>
                    <td>{item.remark}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <p className="ldb-link-preview">
            本次关联保险上浮费合计：<strong className="tabular-nums">{formatMoney(linkedAmount)}</strong>
          </p>
        </div>
        <footer className="vm-modal-footer">
          <button type="button" className="vm-btn vm-btn-ghost" onClick={onClose} data-vm-icon="x">取消</button>
          <button type="button" className="vm-btn vm-btn-primary" disabled={selected.size === 0} onClick={handleConfirm} data-vm-icon="send">
            确认关联
          </button>
        </footer>
      </div>
    </div>
  );
}
