import { useMemo, useState } from "react";

export default function LookupModal({ title, rows, columns, onPick, onClose }) {
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter((row) => JSON.stringify(row).toLowerCase().includes(q));
  }, [rows, query]);

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(15, 23, 42, 0.55)", display: "grid", placeItems: "center", zIndex: 999 }}>
      <div className="glass" style={{ width: "min(960px, 92vw)", maxHeight: "85vh", overflow: "auto", padding: 18, borderRadius: 20 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, marginBottom: 14 }}>
          <div>
            <h3 style={{ margin: 0 }}>{title}</h3>
            <p style={{ margin: "6px 0 0 0", opacity: 0.75 }}>Eintrag auswählen und die ID automatisch übernehmen.</p>
          </div>
          <button className="btn secondary" type="button" onClick={onClose}>Schließen</button>
        </div>
        <input className="input search" placeholder="Suchen..." value={query} onChange={(e) => setQuery(e.target.value)} style={{ marginBottom: 12 }} />
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                {columns.map((col) => <th key={col.key}>{col.label}</th>)}
                <th>Aktion</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((row) => (
                <tr key={row.id}>
                  {columns.map((col) => <td key={col.key}>{String(row[col.key] ?? "")}</td>)}
                  <td><button className="mini-btn" type="button" onClick={() => onPick(row)}>Übernehmen</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
