"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { Search } from "lucide-react";
import { useDeferredValue, useEffect, useRef, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";

type SearchItem = {
  id: string;
  type: "LOT" | "PURCHASE";
  title: string;
  subtitle: string;
  href: string;
};

type TopbarSearchProps = {
  placeholder: string;
};

export function TopbarSearch({ placeholder }: TopbarSearchProps) {
  const router = useRouter();
  const { locale } = useLocale();
  const rootRef = useRef<HTMLDivElement | null>(null);
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<SearchItem[]>([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const deferredQuery = useDeferredValue(query.trim());

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

    document.addEventListener("mousedown", handlePointerDown);
    return () => document.removeEventListener("mousedown", handlePointerDown);
  }, []);

  useEffect(() => {
    let cancelled = false;

    async function loadResults() {
      if (deferredQuery.length < 2) {
        setResults([]);
        setLoading(false);
        return;
      }

      setLoading(true);
      try {
        const response = await fetch(`/api/v1/global-search?q=${encodeURIComponent(deferredQuery)}`, {
          cache: "no-store"
        });
        const payload = (await response.json()) as { data: SearchItem[] };
        if (!cancelled) {
          setResults(response.ok ? payload.data : []);
        }
      } catch {
        if (!cancelled) {
          setResults([]);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
          setOpen(true);
        }
      }
    }

    void loadResults();

    return () => {
      cancelled = true;
    };
  }, [deferredQuery]);

  function openSearchTarget(href: string) {
    setOpen(false);
    router.push(href);
  }

  function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();

    if (results[0]) {
      openSearchTarget(results[0].href);
      return;
    }

    const trimmed = query.trim();
    if (!trimmed) return;
    openSearchTarget(`/lots?search=${encodeURIComponent(trimmed)}`);
  }

  const helperText =
    locale === "id"
      ? {
          searching: "Mencari...",
          empty: "Tidak ada hasil yang cocok.",
          hint: "Ketik minimal 2 karakter",
          lot: "Lot",
          purchase: "Pembelian"
        }
      : {
          searching: "Searching...",
          empty: "No matching results.",
          hint: "Type at least 2 characters",
          lot: "Lot",
          purchase: "Purchase"
        };

  return (
    <div ref={rootRef} className="relative w-full">
      <form onSubmit={handleSubmit}>
        <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
        <input
          value={query}
          onChange={(event) => setQuery(event.target.value)}
          onFocus={() => setOpen(true)}
          className="w-full rounded-xl border border-line/70 bg-slate-50 py-2 pl-10 pr-4 text-sm outline-none transition focus:border-moss/30 focus:bg-white focus:ring-2 focus:ring-moss/15"
          placeholder={placeholder}
          type="text"
        />
      </form>

      {open ? (
        <div className="absolute left-0 right-0 top-[calc(100%+0.5rem)] overflow-hidden rounded-xl border border-line/70 bg-white shadow-panel">
          {query.trim().length < 2 ? (
            <div className="px-4 py-3 text-sm text-slate-500">{helperText.hint}</div>
          ) : loading ? (
            <div className="px-4 py-3 text-sm text-slate-500">{helperText.searching}</div>
          ) : results.length === 0 ? (
            <div className="px-4 py-3 text-sm text-slate-500">{helperText.empty}</div>
          ) : (
            <div className="py-2">
              {results.map((item) => (
                <Link
                  key={`${item.type}-${item.id}`}
                  href={item.href}
                  onClick={() => setOpen(false)}
                  className="flex items-start justify-between gap-4 px-4 py-3 transition hover:bg-slate-50"
                >
                  <div className="min-w-0">
                    <p className="truncate text-sm font-semibold text-ink">{item.title}</p>
                    <p className="truncate text-xs text-slate-500">{item.subtitle}</p>
                  </div>
                  <span className="shrink-0 rounded-full bg-slate-100 px-2 py-1 text-[11px] font-semibold uppercase tracking-[0.06em] text-slate-600">
                    {item.type === "LOT" ? helperText.lot : helperText.purchase}
                  </span>
                </Link>
              ))}
            </div>
          )}
        </div>
      ) : null}
    </div>
  );
}
