/**
 * EntityListFilter — client filter + paginated grid for /e/[class].
 */
"use client";
import Link from "next/link";
import { useMemo, useState } from "react";

interface EntityRow {
  id: string;
  canonical_name: string;
  aliases: string[];
  total_mentions: number;
  documents_count: number;
  enrichment_status: string | null;
}

const PAGE = 60;

export function EntityListFilter({
  entities,
  folder,
}: {
  entities: EntityRow[];
  folder: string;
}) {
  const [q, setQ] = useState("");
  const [page, setPage] = useState(0);
  const [onlyEnriched, setOnlyEnriched] = useState(false);

  const filtered = useMemo(() => {
    let out = entities;
    if (q.trim()) {
      const ql = q.toLowerCase();
      out = out.filter(
        (e) =>
          e.canonical_name.toLowerCase().includes(ql) ||
          e.id.toLowerCase().includes(ql) ||
          e.aliases.some((a) => a.toLowerCase().includes(ql)),
      );
    }
    if (onlyEnriched) {
      out = out.filter((e) => e.enrichment_status === "deep" || e.enrichment_status === "shallow");
    }
    return out;
  }, [entities, q, onlyEnriched]);

  const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE));
  const slice = filtered.slice(page * PAGE, page * PAGE + PAGE);

  return (
    <div>
      <div className="flex flex-wrap items-end gap-3 mb-6 p-3 border border-[rgba(0,255,156,0.15)] bg-[#0a121e] rounded">
        <div className="flex-1 min-w-[200px]">
          <label className="font-mono text-[10px] uppercase tracking-widest text-[#5a6678] block mb-1">
            buscar
          </label>
          <input
            value={q}
            onChange={(e) => {
              setQ(e.target.value);
              setPage(0);
            }}
            placeholder="nome ou alias..."
            className="w-full bg-transparent border border-[rgba(0,255,156,0.20)] focus:border-[#00ff9c] rounded px-2 py-1.5 font-mono text-sm text-[#c8d4e6] outline-none"
          />
        </div>
        <label className="flex items-center gap-2 font-mono text-xs text-[#c8d4e6] cursor-pointer">
          <input
            type="checkbox"
            checked={onlyEnriched}
            onChange={(e) => {
              setOnlyEnriched(e.target.checked);
              setPage(0);
            }}
            className="accent-[#00ff9c]"
          />
          só com enrichment
        </label>
        <div className="font-mono text-xs text-[#5a6678] ml-auto">
          {filtered.length} de {entities.length}
        </div>
      </div>

      <ul className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
        {slice.map((e) => (
          <li key={e.id}>
            <Link
              href={`/e/${folder}/${e.id}`}
              className="block p-2.5 bg-[#0a121e] border border-[rgba(127,219,255,0.18)] hover:border-[#00ff9c] rounded transition"
            >
              <div className="flex items-baseline justify-between gap-2">
                <span className="text-[#c8d4e6] text-sm font-bold truncate flex-1">
                  {e.canonical_name}
                </span>
                <span className="font-mono text-[10px] text-[#00ff9c] flex-shrink-0">
                  {e.total_mentions}×
                </span>
              </div>
              <div className="flex items-center gap-2 mt-1 font-mono text-[10px]">
                <span className="text-[#5a6678] truncate">{e.id}</span>
                {e.enrichment_status && e.enrichment_status !== "none" && (
                  <span
                    className={`px-1 rounded ${
                      e.enrichment_status === "deep"
                        ? "text-[#00ff9c] bg-[rgba(0,255,156,0.08)]"
                        : "text-[#a78bfa] bg-[rgba(167,139,250,0.08)]"
                    }`}
                  >
                    {e.enrichment_status}
                  </span>
                )}
                {e.documents_count > 0 && (
                  <span className="text-[#5a6678]">{e.documents_count} docs</span>
                )}
              </div>
            </Link>
          </li>
        ))}
      </ul>

      {pageCount > 1 && (
        <nav className="mt-6 flex items-center justify-center gap-2 font-mono text-xs">
          <button
            onClick={() => setPage((p) => Math.max(0, p - 1))}
            disabled={page === 0}
            className="px-3 py-1 border border-[rgba(127,219,255,0.30)] rounded disabled:opacity-30 hover:border-[#00ff9c]"
          >
            ←
          </button>
          <span className="text-[#8896aa]">
            página <span className="text-[#00ff9c]">{page + 1}</span> de {pageCount}
          </span>
          <button
            onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
            disabled={page >= pageCount - 1}
            className="px-3 py-1 border border-[rgba(127,219,255,0.30)] rounded disabled:opacity-30 hover:border-[#00ff9c]"
          >
            →
          </button>
        </nav>
      )}
    </div>
  );
}
