"use client";

import { useEffect, useRef, useState } from "react";
import { List, Plus, Pencil, Trash2, Check, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { useLocale } from "@/lib/i18n/provider";
import { useConversationList } from "./use-conversation-list";
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 };

/**
 * Dropdown skin for the general assistant's conversation list — a narrow
 * popover, used in the drawer/mobile layout. The desktop-fullscreen layout
 * uses ConversationSidebar (a persistent list) instead; both share their
 * fetch/rename/delete logic via useConversationList so they can't diverge.
 * The per-recipe chat stays single-threaded, one conversation per recipe,
 * by design — it never uses either of these.
 */
export function ConversationMenu({
  activeId,
  onSelect,
  onCreated,
  onDeletedActive,
  className,
}: {
  activeId: string | null;
  onSelect: (id: string) => void;
  onCreated: (conversation: Conversation) => void;
  onDeletedActive: () => void;
  className?: string;
}) {
  const { locale } = useLocale();
  const [open, setOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
  const {
    t,
    conversations,
    loading,
    load,
    create,
    renamingId,
    renameValue,
    setRenameValue,
    startRename,
    cancelRename,
    submitRename,
    deleteTargetId,
    setDeleteTargetId,
    confirmDelete,
  } = useConversationList(onDeletedActive, activeId);

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

  function handleToggle() {
    setOpen((v) => !v);
    void load();
  }

  async function handleCreate() {
    const created = await create();
    if (!created) return;
    onCreated(created);
    setOpen(false);
  }

  return (
    <div ref={containerRef} className={cn("relative", className)}>
      <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(
                  "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") cancelRename();
                      }}
                      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={cancelRename} 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 text-muted-foreground"
                      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 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>
  );
}
