import { useSearchParams } from 'react-router';
import { Loader2, Search } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { MediaGrid } from './MediaCard';
import { QUERY_PARAM } from './shared';
import { useJellyfinSearch } from './useJellyfinData';

// Search across every video library.
//
// The term is `?q=` — in the URL, not in component state, so a result set is a link and the browser's own
// back button steps through what you looked for. `replace` on every keystroke keeps that history one entry
// per search rather than one per letter.

export const SearchSection = () => {
  const [params, setParams] = useSearchParams();
  const term = params.get(QUERY_PARAM) ?? '';
  const { data, isFetching } = useJellyfinSearch(term);

  const setTerm = (value: string) => {
    const next = new URLSearchParams(params);
    if (value) next.set(QUERY_PARAM, value);
    else next.delete(QUERY_PARAM);
    setParams(next, { replace: true });
  };

  const items = data?.Items ?? [];

  return (
    <div className="flex h-full flex-col">
      <div className="flex items-center gap-2 border-b px-4 py-2">
        <Search className="h-4 w-4 shrink-0 text-muted-foreground" />
        <Input
          value={term}
          onChange={(ev) => setTerm(ev.target.value)}
          placeholder="Search films, shows and episodes"
          className="h-8 border-0 bg-transparent px-0 shadow-none focus-visible:ring-0"
          autoFocus
          spellCheck={false}
        />
        {isFetching && <Loader2 className="h-4 w-4 shrink-0 animate-spin text-muted-foreground" />}
      </div>

      <div className="flex-1 overflow-y-auto p-4">
        {term.trim().length < 2 ? (
          <p className="pt-10 text-center text-xs text-muted-foreground">Type at least two characters.</p>
        ) : items.length ? (
          <MediaGrid items={items} />
        ) : (
          !isFetching && <p className="pt-10 text-center text-xs text-muted-foreground">Nothing matched “{term}”.</p>
        )}
      </div>
    </div>
  );
};
