"use client";

import { FormEvent, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Search, X } from "lucide-react";

type Props = {
  open: boolean;
  onClose: () => void;
};

export function SearchOverlay({ open, onClose }: Props) {
  const router = useRouter();
  const inputRef = useRef<HTMLInputElement>(null);
  const [q, setQ] = useState("");

  useEffect(() => {
    if (!open) return;
    setQ("");
    const t = window.setTimeout(() => inputRef.current?.focus(), 50);
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => {
      window.clearTimeout(t);
      window.removeEventListener("keydown", onKey);
    };
  }, [open, onClose]);

  if (!open) return null;

  const submit = (e: FormEvent) => {
    e.preventDefault();
    const term = q.trim();
    onClose();
    if (!term) {
      router.push("/shop");
      return;
    }
    router.push(`/shop?q=${encodeURIComponent(term)}`);
  };

  return (
    <div
      className="fixed inset-0 z-[80] bg-ot-ink/40 backdrop-blur-[2px]"
      role="dialog"
      aria-modal="true"
      aria-label="Buscar productos"
      onClick={onClose}
    >
      <div
        className="mx-auto mt-[12vh] w-[min(92vw,560px)] bg-ot-cream border border-black/10 shadow-lg"
        onClick={(e) => e.stopPropagation()}
      >
        <form onSubmit={submit} className="flex items-center gap-2 px-4 py-3">
          <Search size={18} className="text-ot-muted shrink-0" />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Buscar prendas, sets, Club 1976…"
            className="flex-1 bg-transparent text-sm outline-none placeholder:text-ot-muted/60 py-2"
            autoComplete="off"
          />
          <button
            type="button"
            aria-label="Cerrar búsqueda"
            className="p-1 text-ot-muted hover:text-ot-ink"
            onClick={onClose}
          >
            <X size={18} />
          </button>
        </form>
        <p className="px-4 pb-3 text-[11px] tracking-[0.12em] uppercase text-ot-muted">
          Enter para ver resultados en el shop
        </p>
      </div>
    </div>
  );
}
