"use client";

import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { MessageCircle, Send, Bot, User, Maximize2, Minimize2, ChefHat, Check, X, Loader2 } from "lucide-react";
import ReactMarkdown from "react-markdown";
import { cn } from "@/lib/utils";
import { ChatHistorySearch } from "./chat-history-search";
import { ConversationMenu, type Conversation } from "./conversation-menu";
import { ConversationSidebar } from "./conversation-sidebar";
import { ShoppingListProposalCard, type ShoppingListProposal } from "./shopping-list-proposal-card";

type RecipeProposal = {
  title: string;
  description?: string;
  baseServings: number;
  recipeType: "dish" | "drink";
  difficulty?: "easy" | "medium" | "hard";
  prepMins?: number;
  cookMins?: number;
  ingredients: Array<{ rawName: string; quantity?: number; unit?: string }>;
  steps: Array<{ instruction: string }>;
};

type ProposalStatus = "pending" | "creating" | "created" | "discarded";

type Message = {
  role: "user" | "assistant";
  content: string;
  proposedRecipe?: RecipeProposal;
  proposalStatus?: ProposalStatus;
  proposedShoppingList?: ShoppingListProposal;
  shoppingProposalStatus?: ProposalStatus;
};

type HistoryEntry = { role: "user" | "assistant"; content: string };

export function CookingAssistantPanel() {
  const t = useTranslations("cookingChat");
  const tCommon = useTranslations("common");
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [fullscreen, setFullscreen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [conversationId, setConversationId] = useState<string | null>(null);
  const bottomRef = useRef<HTMLDivElement>(null);
  const historyLoadedRef = useRef(false);

  async function loadMessages(id: string) {
    try {
      const res = await fetch(`/api/v1/ai/chat-history?conversationId=${id}&limit=50`);
      const json = res.ok ? (await res.json()) as { data?: HistoryEntry[] } : null;
      setMessages(json?.data?.length ? json.data.map((m) => ({ role: m.role, content: m.content })) : []);
    } catch {
      setMessages([]);
    }
  }

  function handleSelectConversation(id: string) {
    setConversationId(id);
    void loadMessages(id);
  }

  function handleConversationCreated(conversation: Conversation) {
    setConversationId(conversation.id);
    setMessages([]);
  }

  function handleActiveConversationDeleted() {
    // Fall back to a fresh conversation rather than leaving the panel
    // pointed at an id that no longer exists.
    fetch("/api/v1/ai/conversations", { method: "POST" })
      .then((res) => (res.ok ? res.json() : null))
      .then((created: Conversation | null) => {
        if (created) {
          setConversationId(created.id);
          setMessages([]);
        }
      })
      .catch(() => {});
  }

  useEffect(() => {
    if (!open || historyLoadedRef.current) return;
    historyLoadedRef.current = true;
    (async () => {
      const listRes = await fetch("/api/v1/ai/conversations");
      const list = listRes.ok ? ((await listRes.json()) as { data: Conversation[] }).data : [];
      const id = list.length > 0
        ? list[0]!.id
        : await fetch("/api/v1/ai/conversations", { method: "POST" })
            .then((res) => (res.ok ? res.json() : null))
            .then((created: Conversation | null) => created?.id ?? null);
      if (!id) return;
      setConversationId(id);
      await loadMessages(id);
    })().catch(() => {});
  }, [open]);

  useEffect(() => {
    if (open && bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, open]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const question = input.trim();
    if (!question || loading) return;

    setInput("");
    setMessages((prev) => [...prev, { role: "user", content: question }]);
    setLoading(true);

    try {
      const res = await fetch("/api/v1/ai/cooking-chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question, conversationId: conversationId ?? undefined }),
      });
      const data = await res.json() as {
        answer?: string;
        error?: string;
        proposedRecipe?: RecipeProposal;
        proposedShoppingList?: ShoppingListProposal;
      };
      setMessages((prev) => [
        ...prev,
        {
          role: "assistant",
          content: data.answer ?? t("sorry"),
          proposedRecipe: data.proposedRecipe,
          proposalStatus: data.proposedRecipe ? "pending" : undefined,
          proposedShoppingList: data.proposedShoppingList,
          shoppingProposalStatus: data.proposedShoppingList ? "pending" : undefined,
        },
      ]);
    } catch {
      setMessages((prev) => [
        ...prev,
        { role: "assistant", content: t("error") },
      ]);
    } finally {
      setLoading(false);
    }
  };

  async function handleCreateProposal(index: number) {
    const proposal = messages[index]?.proposedRecipe;
    if (!proposal) return;

    setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "creating" } : m)));

    try {
      const res = await fetch("/api/v1/recipes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: proposal.title,
          description: proposal.description,
          baseServings: proposal.baseServings,
          recipeType: proposal.recipeType,
          difficulty: proposal.difficulty,
          prepMins: proposal.prepMins,
          cookMins: proposal.cookMins,
          visibility: "private",
          aiGenerated: true,
          ingredients: proposal.ingredients.map((ing, i) => ({ rawName: ing.rawName, quantity: ing.quantity, unit: ing.unit, order: i })),
          steps: proposal.steps.map((step, i) => ({ instruction: step.instruction, order: i })),
        }),
      });
      if (!res.ok) {
        setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "pending" } : m)));
        toast.error(t("proposalCreateFailed"));
        return;
      }
      const { id } = await res.json() as { id: string };
      setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "created" } : m)));
      toast.success(t("proposalCreated"));
      router.push(`/recipes/${id}/edit`);
    } catch {
      setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "pending" } : m)));
      toast.error(t("proposalCreateFailed"));
    }
  }

  function handleDiscardProposal(index: number) {
    setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, proposalStatus: "discarded" } : m)));
  }

  function handleShoppingProposalStatusChange(index: number, status: ProposalStatus) {
    setMessages((prev) => prev.map((m, i) => (i === index ? { ...m, shoppingProposalStatus: status } : m)));
  }

  const suggestions = [
    t("suggestion1"),
    t("suggestion2"),
    t("suggestion3"),
    t("suggestion4"),
  ];

  return (
    <>
      <Button
        variant="default"
        size="icon"
        // bottom-16 (not bottom-6, like the per-recipe chat button) clears the
        // recipe list's floating bulk-action bar, which occupies the bottom-4
        // to bottom-8 band while select mode is active.
        className="fixed bottom-16 right-6 h-12 w-12 rounded-full shadow-lg z-40"
        onClick={() => setOpen(true)}
        aria-label={t("ariaLabel")}
      >
        <MessageCircle className="h-5 w-5" />
      </Button>

      <Sheet open={open} onOpenChange={(v) => { setOpen(v); if (!v) setFullscreen(false); }}>
        <SheetContent
          side="right"
          className={cn(
            "p-0",
            fullscreen ? "!w-screen !max-w-none !h-screen !inset-0 flex flex-row" : "flex flex-col w-full sm:w-[420px]"
          )}
        >
          {fullscreen && (
            <ConversationSidebar
              className="hidden md:flex w-64 shrink-0"
              activeId={conversationId}
              onSelect={handleSelectConversation}
              onCreated={handleConversationCreated}
              onDeletedActive={handleActiveConversationDeleted}
            />
          )}
          <div className="flex flex-col flex-1 min-w-0 h-full">
          <SheetHeader className="px-4 py-3 pr-10 border-b shrink-0">
            <div className="flex items-center justify-between gap-2">
              <SheetTitle className="text-base flex items-center gap-2">
                <Bot className="h-4 w-4 text-primary" />
                {t("title")}
              </SheetTitle>
              <div className="flex items-center gap-0.5">
                <button
                  type="button"
                  onClick={() => setFullscreen((v) => !v)}
                  aria-label={fullscreen ? tCommon("collapse") : tCommon("expand")}
                  className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
                >
                  {fullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
                </button>
                <ChatHistorySearch />
                {/* On desktop fullscreen, ConversationSidebar (left) replaces this
                    dropdown — kept for mobile fullscreen and the normal drawer,
                    where there's no room for a persistent sidebar. */}
                <ConversationMenu
                  className={cn(fullscreen && "md:hidden")}
                  activeId={conversationId}
                  onSelect={handleSelectConversation}
                  onCreated={handleConversationCreated}
                  onDeletedActive={handleActiveConversationDeleted}
                />
              </div>
            </div>
            <p className="text-xs text-muted-foreground text-left">{t("subtitle")}</p>
          </SheetHeader>

          <div className="flex-1 overflow-y-auto px-4 py-4 space-y-4 min-h-0">
            {messages.length === 0 && (
              <div className="space-y-3">
                <p className="text-sm text-muted-foreground text-center py-4">
                  {t("intro")}
                </p>
                <div className="space-y-2">
                  {suggestions.map((s) => (
                    <button
                      key={s}
                      onClick={() => setInput(s)}
                      className="w-full text-left text-sm px-3 py-2 rounded-lg border bg-muted/50 hover:bg-muted transition-colors"
                    >
                      {s}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {messages.map((msg, i) => (
              <div key={i} className="space-y-2">
                <div
                  className={cn(
                    "flex gap-2 items-start",
                    msg.role === "user" && "flex-row-reverse"
                  )}
                >
                  <div className={cn(
                    "h-7 w-7 shrink-0 rounded-full flex items-center justify-center",
                    msg.role === "user"
                      ? "bg-primary text-primary-foreground"
                      : "bg-muted text-muted-foreground"
                  )}>
                    {msg.role === "user" ? <User className="h-3.5 w-3.5" /> : <Bot className="h-3.5 w-3.5" />}
                  </div>
                  <div className={cn(
                    "rounded-xl px-3 py-2 text-sm max-w-[80%] leading-relaxed",
                    msg.role === "user"
                      ? "bg-primary text-primary-foreground whitespace-pre-wrap"
                      : "bg-muted space-y-2 [&_ul]:list-disc [&_ol]:list-decimal [&_ul]:pl-4 [&_ol]:pl-4 [&_strong]:font-semibold [&_li]:my-0.5"
                  )}>
                    {msg.role === "assistant" ? (
                      <ReactMarkdown>{msg.content}</ReactMarkdown>
                    ) : (
                      msg.content
                    )}
                  </div>
                </div>

                {msg.proposedRecipe && (
                  <div className="ml-9 rounded-lg border bg-card p-3 space-y-2 max-w-[80%]">
                    <div className="flex items-center gap-2">
                      <ChefHat className="h-3.5 w-3.5 text-primary shrink-0" />
                      <span className="font-medium text-sm truncate">{msg.proposedRecipe.title}</span>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {t("proposalSummary", {
                        ingredients: msg.proposedRecipe.ingredients.length,
                        steps: msg.proposedRecipe.steps.length,
                      })}
                    </p>
                    {msg.proposalStatus === "created" ? (
                      <p className="text-xs text-primary flex items-center gap-1"><Check className="h-3 w-3" />{t("proposalCreated")}</p>
                    ) : msg.proposalStatus === "discarded" ? (
                      <p className="text-xs text-muted-foreground flex items-center gap-1"><X className="h-3 w-3" />{t("proposalDiscarded")}</p>
                    ) : (
                      <div className="flex gap-2">
                        <Button
                          size="sm"
                          className="h-7 text-xs gap-1"
                          disabled={msg.proposalStatus === "creating"}
                          onClick={() => void handleCreateProposal(i)}
                        >
                          {msg.proposalStatus === "creating"
                            ? <Loader2 className="h-3 w-3 animate-spin" />
                            : <Check className="h-3 w-3" />}
                          {t("proposalCreateButton")}
                        </Button>
                        <Button
                          size="sm"
                          variant="ghost"
                          className="h-7 text-xs"
                          disabled={msg.proposalStatus === "creating"}
                          onClick={() => handleDiscardProposal(i)}
                        >
                          {t("proposalDiscardButton")}
                        </Button>
                      </div>
                    )}
                  </div>
                )}

                {msg.proposedShoppingList && msg.shoppingProposalStatus && (
                  <ShoppingListProposalCard
                    proposal={msg.proposedShoppingList}
                    status={msg.shoppingProposalStatus}
                    onStatusChange={(status) => handleShoppingProposalStatusChange(i, status)}
                  />
                )}
              </div>
            ))}

            {loading && (
              <div className="flex gap-2 items-start">
                <div className="h-7 w-7 shrink-0 rounded-full flex items-center justify-center bg-muted text-muted-foreground">
                  <Bot className="h-3.5 w-3.5" />
                </div>
                <div className="rounded-xl px-3 py-2 bg-muted">
                  <span className="flex gap-1">
                    <span className="w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:0ms]" />
                    <span className="w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:150ms]" />
                    <span className="w-1.5 h-1.5 rounded-full bg-muted-foreground animate-bounce [animation-delay:300ms]" />
                  </span>
                </div>
              </div>
            )}

            <div ref={bottomRef} />
          </div>

          <form onSubmit={handleSubmit} className="px-4 py-3 border-t shrink-0 flex gap-2">
            <Input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder={t("inputPlaceholder")}
              disabled={loading}
              className="flex-1"
              autoComplete="off"
            />
            <Button type="submit" size="icon" disabled={loading || !input.trim()} aria-label={t("send")}>
              <Send className="h-4 w-4" />
            </Button>
          </form>
          </div>
        </SheetContent>
      </Sheet>
    </>
  );
}
