import React, { useEffect, useId, useState } from 'react';
import { createPortal } from 'react-dom';
import { X } from 'lucide-react';

interface LedgerDetailPopoverProps {
  label: string;
  title?: string;
  triggerClassName?: string;
  children: React.ReactNode;
  footer?: React.ReactNode;
}

export function LedgerDetailPopover({
  label,
  title,
  triggerClassName = '',
  children,
  footer,
}: LedgerDetailPopoverProps) {
  const [open, setOpen] = useState(false);
  const dialogId = useId();
  const titleId = useId();

  useEffect(() => {
    if (!open) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') setOpen(false);
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open]);

  const close = () => setOpen(false);

  return (
    <>
      <button
        type="button"
        className={`ldb-detail-popover-trigger ldb-cell-clickable cursor-pointer ${triggerClassName}`.trim()}
        aria-haspopup="dialog"
        aria-expanded={open}
        aria-controls={open ? dialogId : undefined}
        onClick={() => setOpen(true)}
      >
        {label}
      </button>
      {open && createPortal(
        <div className="vm-modal-backdrop ldb-detail-card-backdrop" role="presentation" onClick={close}>
          <div
            id={dialogId}
            className="vm-modal ldb-detail-card-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby={titleId}
            onClick={(event) => event.stopPropagation()}
          >
            <header className="vm-modal-header ldb-detail-card-header">
              <h2 id={titleId} className="vm-modal-title">{title ?? label}</h2>
              <button type="button" className="vm-modal-close" onClick={close} aria-label="关闭">
                <X size={18} aria-hidden />
              </button>
            </header>
            <div className="vm-modal-body ldb-detail-card-body">
              <div className="ldb-detail-card-summary" aria-label="汇总">
                <span className="ldb-detail-card-summary-label">合计金额</span>
                <span className="ldb-detail-card-summary-value tabular-nums">{label}</span>
              </div>
              <div className="ldb-detail-card-content">{children}</div>
            </div>
            {footer && <footer className="vm-modal-footer ldb-detail-card-footer">{footer}</footer>}
          </div>
        </div>,
        document.body,
      )}
    </>
  );
}

interface LedgerDetailTableProps {
  columns: { key: string; title: string; align?: 'left' | 'right' }[];
  rows: Record<string, React.ReactNode>[];
  emptyText?: string;
}

export function LedgerDetailTable({ columns, rows, emptyText = '暂无明细' }: LedgerDetailTableProps) {
  if (!rows.length) {
    return <p className="ldb-detail-popover-empty">{emptyText}</p>;
  }

  return (
    <>
      <p className="ldb-detail-card-meta">共 {rows.length} 条明细记录</p>
      <div className="ldb-detail-card-table-wrap">
        <table className="ldb-detail-popover-table">
          <thead>
            <tr>
              {columns.map((col) => (
                <th
                  key={col.key}
                  className={col.align === 'right' ? 'ldb-detail-col-amount' : undefined}
                >
                  {col.title}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((row, index) => (
              <tr key={index}>
                {columns.map((col) => (
                  <td
                    key={col.key}
                    className={col.align === 'right' ? 'ldb-detail-col-amount tabular-nums' : undefined}
                  >
                    {row[col.key] ?? ''}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}
