"use client";

import { useEffect, useRef, useState } from "react";
import { useTranslations } from "next-intl";
import { List, Plus, Pencil, Trash2, Check, X } from "lucide-react";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { useLocale } from "@/lib/i18n/provider";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

export type Conversation = { id: string; title: string | null; createdAt: string; updatedAt: string };

/**
 * Lists, creates, renames, and deletes the general assistant's conversations
 * — the homepage chat can hold more than one thread, unlike the per-recipe
 * chat (which stays single-threaded, one conversation per recipe, by design).
 */
export function ConversationMenu({
  activeId,
  onSelect,
  onCreated,
  onDeletedActive,
}: {
  activeId: string | null;
  onSelect: (id: string) => void;
  onCreated: (conversation: Conversation) => void;
  onDeletedActive: () => void;
}) {
  const t = useTranslations("conversations");
  const { locale } = useLocale();
  const [open, setOpen] = useState(false);
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(false);
  const [renamingId, setRenamingId] = useState<string | null>(null);
  const [renameValue, setRenameValue] = useState("");
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const loadedRef = useRef(false);

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

  async function loadConversations() {
    setLoading(true);
    try {
      const res = await fetch("/api/v1/ai/conversations");
      if (!res.ok) return;
      const json = await res.json() as { data: Conversation[] };
      setConversations(json.data);
    } finally {
      setLoading(false);
    }
  }

  function handleToggle() {
    setOpen((v) => !v);
    if (!loadedRef.current) {
      loadedRef.current = true;
      void loadConversations();
    }
  }

  async function handleCreate() {
    const res = await fetch("/api/v1/ai/conversations", { method: "POST" });
    if (!res.ok) {
      toast.error(t("createFailed"));
      return;
    }
    const created = await res.json() as Conversation;
    setConversations((prev) => [created, ...prev]);
    onCreated(created);
    setOpen(false);
  }

  function startRename(conversation: Conversation) {
    setRenamingId(conversation.id);
    setRenameValue(conversation.title ?? "");
  }

  async function submitRename() {
    if (!renamingId) return;
    const id = renamingId;
    const title = renameValue.trim() || null;
    setRenamingId(null);
    const res = await fetch(`/api/v1/ai/conversations/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title }),
    });
    if (!res.ok) {
      toast.error(t("renameFailed"));
      return;
    }
    setConversations((prev) => prev.map((c) => (c.id === id ? { ...c, title } : c)));
  }

  async function confirmDelete() {
    const id = deleteTargetId;
    setDeleteTargetId(null);
    if (!id) return;
    const res = await fetch(`/api/v1/ai/conversations/${id}`, { method: "DELETE" });
    if (!res.ok) {
      toast.error(t("deleteFailed"));
      return;
    }
    setConversations((prev) => prev.filter((c) => c.id !== id));
    if (id === activeId) onDeletedActive();
  }

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

      {open && (
        <div className="absolute right-0 top-full mt-1 w-72 rounded-lg border bg-popover shadow-lg z-50 max-h-96 flex flex-col">
          <div className="p-1.5 border-b">
            <button
              type="button"
              onClick={() => void handleCreate()}
              className="w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-muted transition-colors text-left"
            >
              <Plus className="h-3.5 w-3.5" />
              {t("newConversation")}
            </button>
          </div>
          <div className="overflow-y-auto flex-1 p-1">
            {loading && <p className="text-xs text-muted-foreground text-center py-4">{t("loading")}</p>}
            {!loading && conversations.length === 0 && (
              <p className="text-xs text-muted-foreground text-center py-4">{t("empty")}</p>
            )}
            {!loading && conversations.map((c) => (
              <div
                key={c.id}
                className={cn(
                  "group flex items-center gap-1 px-2 py-1.5 rounded-md text-sm",
                  c.id === activeId ? "bg-accent" : "hover:bg-muted/60"
                )}
              >
                {renamingId === c.id ? (
                  <>
                    <input
                      autoFocus
                      value={renameValue}
                      onChange={(e) => setRenameValue(e.target.value)}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") void submitRename();
                        if (e.key === "Escape") setRenamingId(null);
                      }}
                      maxLength={100}
                      className="flex-1 min-w-0 bg-transparent border-b border-primary text-sm outline-none"
                    />
                    <button type="button" onClick={() => void submitRename()} className="p-1 rounded-md hover:bg-muted shrink-0" aria-label={t("renameSave")}>
                      <Check className="h-3.5 w-3.5" />
                    </button>
                    <button type="button" onClick={() => setRenamingId(null)} className="p-1 rounded-md hover:bg-muted shrink-0" aria-label={t("renameCancel")}>
                      <X className="h-3.5 w-3.5" />
                    </button>
                  </>
                ) : (
                  <>
                    <button
                      type="button"
                      onClick={() => { onSelect(c.id); setOpen(false); }}
                      className="flex-1 min-w-0 text-left truncate"
                    >
                      <span className="truncate block">{c.title || t("untitled")}</span>
                      <span className="text-xs text-muted-foreground">
                        {new Date(c.updatedAt).toLocaleDateString(locale, { month: "short", day: "numeric" })}
                      </span>
                    </button>
                    <button
                      type="button"
                      onClick={() => startRename(c)}
                      className="p-1 rounded-md hover:bg-muted shrink-0 opacity-0 group-hover:opacity-100 transition-opacity"
                      aria-label={t("renameAriaLabel")}
                    >
                      <Pencil className="h-3.5 w-3.5" />
                    </button>
                    <button
                      type="button"
                      onClick={() => setDeleteTargetId(c.id)}
                      className="p-1 rounded-md hover:bg-muted shrink-0 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground"
                      aria-label={t("deleteAriaLabel")}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      <AlertDialog open={!!deleteTargetId} onOpenChange={(v) => { if (!v) setDeleteTargetId(null); }}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("deleteConfirmTitle")}</AlertDialogTitle>
            <AlertDialogDescription>{t("deleteConfirmDescription")}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("deleteCancel")}</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => { void confirmDelete(); }}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {t("deleteConfirm")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
