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

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

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

  const filteredOrders = useMemo(() => {
    if (!record) return [];
    return orders.filter((item) => item.plateNo === record.plateNo && item.bearBy === '客户承担');
  }, [record, orders]);

  const linkedAmount = useMemo(
    () => filteredOrders.filter((item) => selected.has(item.id)).reduce((sum, item) => sum + item.amount, 0),
    [filteredOrders, 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="maintenance-link-title"
        onClick={(e) => e.stopPropagation()}
      >
        <header className="vm-modal-header">
          <h2 id="maintenance-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>完成日期</th>
                  <th className="ldb-col-money">金额</th>
                </tr>
              </thead>
              <tbody>
                {filteredOrders.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="ldb-receipt-empty">暂无待关联的维修/保养单</td>
                  </tr>
                ) : filteredOrders.map((item) => (
                  <tr key={item.id}>
                    <td className="ldb-col-check">
                      <input
                        type="checkbox"
                        checked={selected.has(item.id)}
                        onChange={() => toggle(item.id)}
                        aria-label={`选择 ${item.orderNo}`}
                      />
                    </td>
                    <td>{item.orderNo}</td>
                    <td>{item.type}</td>
                    <td className="tabular-nums">{item.completedAt}</td>
                    <td className="ldb-col-money tabular-nums">{formatMoney(item.amount)}</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}>取消</button>
          <button type="button" className="vm-btn vm-btn-primary" disabled={selected.size === 0} onClick={handleConfirm}>
            确认关联
          </button>
        </footer>
      </div>
    </div>
  );
}
