// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
"use client";
import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useLang } from "./LangContext";

export interface Suggestion {
  id: string;
  adresse: string | null;
  apt: string | null;
  municipalite: string | null;
  typeProp: string;
}

export default function SearchBox({
  onPick,
  placeholder,
}: {
  /** Si fourni : appelé au choix d'une adresse (le champ se vide) au lieu de naviguer. */
  onPick?: (s: Suggestion) => void;
  placeholder?: string;
}) {
  const { t } = useLang();
  const router = useRouter();
  const [q, setQ] = useState("");
  const [sugg, setSugg] = useState<Suggestion[]>([]);
  const [open, setOpen] = useState(false);
  const [searched, setSearched] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);

  const onChange = (value: string) => {
    setQ(value);
    if (timer.current) clearTimeout(timer.current);
    if (value.trim().length < 3) {
      setSugg([]);
      setSearched(false);
      return;
    }
    timer.current = setTimeout(async () => {
      const res = await fetch(`/api/search?q=${encodeURIComponent(value)}`);
      const data = (await res.json()) as { results: Suggestion[] };
      setSugg(data.results);
      setSearched(true);
      setOpen(true);
    }, 200);
  };

  return (
    <div className="relative w-full">
      <input
        value={q}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setOpen(true)}
        onBlur={() => setTimeout(() => setOpen(false), 200)}
        placeholder={placeholder ?? t("searchPlaceholder")}
        className="vp-input text-base"
        aria-label={placeholder ?? t("searchPlaceholder")}
      />
      {open && sugg.length > 0 && (
        <ul className="absolute z-[1200] mt-2 w-full overflow-hidden rounded-[10px] border-[1.5px] border-ink bg-surface shadow-[6px_6px_0_rgba(20,24,20,0.85)]">
          {sugg.map((s) => (
            <li key={s.id} className="border-b border-[rgba(20,24,20,0.1)] last:border-0">
              <button
                className="flex w-full items-baseline justify-between gap-2 px-4 py-3 text-left transition-colors hover:bg-lime-soft"
                onMouseDown={() => {
                  if (onPick) {
                    onPick(s);
                    setQ("");
                    setSugg([]);
                    setSearched(false);
                  } else {
                    router.push(`/estimation/${s.id}`);
                  }
                }}
              >
                <span className="vp-display font-bold">
                  {s.adresse}
                  {s.apt ? ` app. ${s.apt}` : ""}
                </span>
                <span className="vp-mono shrink-0 text-[11px] uppercase tracking-[0.05em] text-ink-3">
                  {s.municipalite}
                </span>
              </button>
            </li>
          ))}
        </ul>
      )}
      {open && searched && sugg.length === 0 && q.trim().length >= 3 && (
        <div className="vp-mono absolute z-[1200] mt-2 w-full rounded-[10px] border-[1.5px] border-ink bg-surface px-4 py-3 text-[12px] uppercase tracking-[0.04em] text-ink-2 shadow-[6px_6px_0_rgba(20,24,20,0.85)]">
          {t("searchNoResult")}
        </div>
      )}
    </div>
  );
}
