"use client";

import { Search } from "lucide-react";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { getPosterUrl } from "@/lib/tmdb";
import { cn } from "@/lib/utils";

interface SearchResult {
  id: number;
  title: string;
  release_date: string;
  poster_path: string | null;
  overview: string;
}

export function SearchBar({ autoFocus = false }: { autoFocus?: boolean }) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<SearchResult[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (!query.trim()) {
      return;
    }

    const controller = new AbortController();
    const timeout = setTimeout(async () => {
      setLoading(true);
      try {
        const response = await fetch(
          `/api/search?q=${encodeURIComponent(query)}`,
          { signal: controller.signal },
        );
        const data = (await response.json()) as { results: SearchResult[] };
        setResults(data.results ?? []);
        setOpen(true);
      } catch (error) {
        if ((error as Error).name !== "AbortError") {
          setResults([]);
        }
      } finally {
        setLoading(false);
      }
    }, 300);

    return () => {
      clearTimeout(timeout);
      controller.abort();
    };
  }, [query]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (!containerRef.current?.contains(event.target as Node)) {
        setOpen(false);
      }
    }

    if (open) {
      document.addEventListener("click", handleClickOutside);
    }

    return () => document.removeEventListener("click", handleClickOutside);
  }, [open]);

  return (
    <div
      ref={containerRef}
      className={cn("relative w-full max-w-2xl", open && "z-50")}
    >
      <div className="relative">
        <Search className="pointer-events-none absolute left-4 top-1/2 h-5 w-5 -translate-y-1/2 text-amber-200/50" />
        <input
          autoFocus={autoFocus}
          type="search"
          name="movie-search"
          autoComplete="off"
          autoCorrect="off"
          autoCapitalize="off"
          spellCheck={false}
          data-1p-ignore
          data-lpignore="true"
          data-bwignore
          data-form-type="other"
          value={query}
          onChange={(event) => {
            const value = event.target.value;
            setQuery(value);
            if (!value.trim()) {
              setResults([]);
              setOpen(false);
            }
          }}
          onFocus={() => query.trim() && setOpen(true)}
          placeholder="Search for a movie..."
          className="w-full rounded-2xl border border-white/10 bg-white/5 py-4 pl-12 pr-4 text-base text-white outline-none transition focus:border-amber-400/40 focus:bg-white/[0.07] focus:ring-2 focus:ring-amber-400/20"
        />
      </div>

      {open && (
        <ul
          role="listbox"
          className="absolute z-50 mt-2 w-full overflow-hidden rounded-2xl border border-white/10 bg-slate-950 shadow-2xl"
        >
          {loading && (
            <li className="px-4 py-3 text-sm text-slate-400">Searching...</li>
          )}
          {!loading && results.length === 0 && (
            <li className="px-4 py-3 text-sm text-slate-400">No results found</li>
          )}
          {!loading &&
            results.map((result) => {
              const poster = getPosterUrl(result.poster_path, "w185");
              const year = result.release_date?.slice(0, 4);

              return (
                <li key={result.id} role="option" aria-selected={false}>
                  <Link
                    href={`/movie/${result.id}`}
                    prefetch
                    onClick={() => setOpen(false)}
                    className="flex items-center gap-3 border-b border-white/5 px-4 py-3 transition hover:bg-white/5 last:border-b-0"
                  >
                    <div className="relative h-14 w-10 shrink-0 overflow-hidden rounded-md bg-slate-800">
                      {poster ? (
                        <img
                          src={poster}
                          alt=""
                          className="absolute inset-0 h-full w-full object-cover"
                        />
                      ) : (
                        <div className="flex h-full items-center justify-center text-[10px] text-slate-500">
                          N/A
                        </div>
                      )}
                    </div>
                    <div className="min-w-0">
                      <p className="truncate font-medium text-white">
                        {result.title}
                        {year ? (
                          <span className="ml-2 font-normal text-slate-400">
                            ({year})
                          </span>
                        ) : null}
                      </p>
                      <p className="line-clamp-1 text-sm text-slate-400">
                        {result.overview || "No overview available"}
                      </p>
                    </div>
                  </Link>
                </li>
              );
            })}
        </ul>
      )}
    </div>
  );
}