import Link from "next/link";
import { buttonClass } from "@/components/ui";

/** No-JS GET filter form: state lives in the URL so views are shareable and back-button friendly. */
export function FilterBar({
  action,
  q,
  status,
  statuses,
  hidden,
  placeholder = "Search…",
}: {
  action: string;
  q?: string;
  status?: string;
  statuses?: readonly string[];
  hidden?: Record<string, string>;
  placeholder?: string;
}) {
  return (
    <form action={action} method="get" role="search" className="flex flex-wrap items-center gap-2 border-b border-border p-3">
      {Object.entries(hidden ?? {}).map(([k, v]) => (
        <input key={k} type="hidden" name={k} value={v} />
      ))}
      <label className="sr-only" htmlFor="q">Search</label>
      <input id="q" name="q" defaultValue={q} placeholder={placeholder} maxLength={100} className="h-9 w-56 rounded-md border border-border bg-card px-3 text-sm" />
      {statuses ? (
        <>
          <label className="sr-only" htmlFor="status">Status</label>
          <select id="status" name="status" defaultValue={status ?? ""} className="h-9 rounded-md border border-border bg-card px-2 text-sm">
            <option value="">All statuses</option>
            {statuses.map((s) => (
              <option key={s} value={s}>{s.replaceAll("_", " ").toLowerCase()}</option>
            ))}
          </select>
        </>
      ) : null}
      <button type="submit" className={buttonClass("secondary")}>Filter</button>
      {q || status ? <Link href={action} className={buttonClass("ghost")}>Reset</Link> : null}
    </form>
  );
}
