"use client";

import { useEffect, useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";

// Live search. Typing rewrites the `q` param so the server re-queries the whole
// table rather than filtering only the rows on the current page — otherwise
// "sou" would miss South Park whenever it sits on a later page.
export function InventorySearch({
  kind,
  tier,
  initialQuery,
  placeholder,
  label,
}: {
  kind: string;
  tier: string;
  initialQuery: string;
  placeholder: string;
  label: string;
}) {
  const router = useRouter();
  const [value, setValue] = useState(initialQuery);
  const [isPending, startTransition] = useTransition();
  const latest = useRef(initialQuery);

  useEffect(() => {
    // Only navigate when the debounced value differs from what the URL holds,
    // so re-renders coming back from the server do not loop.
    if (value === latest.current) return;

    const timer = setTimeout(() => {
      latest.current = value;
      const params = new URLSearchParams();
      if (kind !== "movie") params.set("kind", kind);
      // Searching must not silently drop the tier filter back to live.
      if (tier !== "live") params.set("tier", tier);
      if (value.trim()) params.set("q", value.trim());
      const queryString = params.toString();

      startTransition(() => {
        router.replace(queryString ? "/admin/inventory?" + queryString : "/admin/inventory", {
          scroll: false,
        });
      });
    }, 250);

    return () => clearTimeout(timer);
  }, [value, kind, tier, router]);

  return (
    <div className="admin-panel flex flex-col gap-3 p-4 sm:flex-row sm:items-center">
      <label className="sr-only" htmlFor="inventory-q">{label}</label>
      <input
        id="inventory-q"
        name="q"
        type="search"
        value={value}
        onChange={(event) => setValue(event.target.value)}
        placeholder={placeholder}
        autoComplete="off"
        className="min-h-10 flex-1 rounded-md border border-admin-line bg-admin-subpanel px-3 text-sm text-admin-text outline-none focus:border-admin-accent"
      />
      <span className={"text-xs " + (isPending ? "text-admin-accent" : "text-admin-muted")}>
        {isPending ? "Searching…" : value ? "Filtered" : "All"}
      </span>
      {value ? (
        <button
          type="button"
          onClick={() => setValue("")}
          className="px-3 py-2 text-sm font-medium text-admin-accent"
        >
          Clear
        </button>
      ) : null}
    </div>
  );
}
