"use client";

import type { CatalogKind } from "@/lib/catalog";
import { useRouter } from "next/navigation";
import { useEffect, useState, useTransition } from "react";

type CatalogControlsProps = {
  kind: CatalogKind;
  query: string;
  collectionOnly: boolean;
};

function buildHref(kind: CatalogKind, query: string, collectionOnly: boolean) {
  const params = new URLSearchParams();
  params.set("tab", kind);

  const trimmedQuery = query.trim();
  if (trimmedQuery) {
    params.set("q", trimmedQuery);
  }

  if (collectionOnly) {
    params.set("collection", "1");
  }

  return "/?" + params.toString();
}

export function CatalogControls({ kind, query, collectionOnly }: CatalogControlsProps) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [searchText, setSearchText] = useState(query);
  const [onlyCollection, setOnlyCollection] = useState(collectionOnly);


  useEffect(() => {
    const timeout = window.setTimeout(() => {
      const href = buildHref(kind, searchText, onlyCollection);
      startTransition(() => router.replace(href, { scroll: false }));
    }, 250);

    return () => window.clearTimeout(timeout);
  }, [kind, onlyCollection, router, searchText, startTransition]);

  return (
    <div className="ampelos-panel mt-5 grid gap-3 p-4 md:grid-cols-[1fr_auto] md:items-center">
      <label className="min-w-0">
        <span className="sr-only">Search catalog</span>
        <input
          name="q"
          value={searchText}
          onChange={(event) => setSearchText(event.target.value)}
          placeholder={kind === "movies" ? "Search movies" : kind === "television" ? "Search television" : "Search music"}
          className="ampelos-input h-11 w-full rounded-md px-3 text-sm outline-none"
        />
      </label>
      <label className="ampelos-ghost-button flex h-11 items-center gap-2 px-3 text-sm font-medium">
        <input
          type="checkbox"
          name="collection"
          checked={onlyCollection}
          onChange={(event) => setOnlyCollection(event.target.checked)}
          className="h-4 w-4 accent-ampelos-gold"
        />
        Dionysus collection
      </label>
    </div>
  );
}
