"use client";

import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { Search, X, Bot, User } from "lucide-react";
import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";

type SearchResult = {
  id: string;
  role: "user" | "assistant";
  content: string;
  createdAt: string;
  recipeId: string | null;
  recipeTitle: string | null;
};

/**
 * Search across the user's own AI-chat history. With `recipeId` set, scopes
 * to that recipe's conversation; omit it to search everything the user has
 * ever asked (both per-recipe chats and the general cooking assistant).
 */
export function ChatHistorySearch({ recipeId }: { recipeId?: string }) {
  const t = useTranslations("chatHistory");
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<SearchResult[]>([]);
  const [loading, setLoading] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  useEffect(() => {
    if (!query.trim()) return;
    const timeout = setTimeout(() => {
      setLoading(true);
      const params = new URLSearchParams({ q: query.trim() });
      if (recipeId) params.set("recipeId", recipeId);
      fetch(`/api/v1/ai/chat-history?${params.toString()}`)
        .then((res) => (res.ok ? res.json() : null))
        .then((json: { data?: SearchResult[] } | null) => setResults(json?.data ?? []))
        .catch(() => setResults([]))
        .finally(() => setLoading(false));
    }, 300);
    return () => clearTimeout(timeout);
  }, [query, recipeId]);

  return (
    <div ref={containerRef} className="relative">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className="p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground"
        aria-label={t("searchAriaLabel")}
      >
        <Search className="h-4 w-4" />
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-1 w-80 rounded-lg border bg-popover shadow-lg z-50 max-h-96 flex flex-col">
          <div className="p-2 border-b flex items-center gap-1">
            <Input
              autoFocus
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder={t("searchPlaceholder")}
              className="h-8 text-sm"
            />
            <button
              type="button"
              onClick={() => setOpen(false)}
              className="p-1.5 rounded-md hover:bg-muted text-muted-foreground shrink-0"
              aria-label={t("close")}
            >
              <X className="h-3.5 w-3.5" />
            </button>
          </div>
          <div className="overflow-y-auto flex-1 p-1">
            {loading && <p className="text-xs text-muted-foreground text-center py-4">{t("searching")}</p>}
            {!loading && query.trim() && results.length === 0 && (
              <p className="text-xs text-muted-foreground text-center py-4">{t("noResults")}</p>
            )}
            {!loading && query.trim() && results.map((r) => (
              <div key={r.id} className="p-2 rounded-md hover:bg-muted/50 text-sm space-y-1">
                <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                  {r.role === "user" ? <User className="h-3 w-3" /> : <Bot className="h-3 w-3" />}
                  <span>{new Date(r.createdAt).toLocaleDateString()}</span>
                  {r.recipeTitle && !recipeId && (
                    <span className="truncate">· {r.recipeTitle}</span>
                  )}
                </div>
                <p className={cn("line-clamp-2", r.role === "user" && "font-medium")}>{r.content}</p>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
