import { useEffect, useRef, useState } from "react";
import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { Loader2, MessageCircle, Send } from "lucide-react";
import { toast } from "sonner";
import { loadBudThread, sendBudMessage, type BudMessage } from "@/lib/chatbud.functions";

export const Route = createFileRoute("/chatbud")({
  head: () => ({
    meta: [
      { title: "ChatBud — Conversational AI Companion | Gatavase Corporation" },
      {
        name: "description",
        content:
          "ChatBud is Gatavase Corporation's conversational companion. Ask about services, products and projects — your conversation is saved so you can pick it up later.",
      },
      { property: "og:title", content: "ChatBud — Gatavase conversational AI" },
      {
        property: "og:description",
        content: "Start a conversation with ChatBud and keep your chat history across visits.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
    ],
    links: [{ rel: "canonical", href: "/chatbud" }],
  }),
  component: ChatBudPage,
});

const KEY = "gatavase-chatbud-session";
const STARTERS = [
  "What can Gatavase build for my business?",
  "How does the Gatavase AI Creative Suite work?",
  "I need a mobile app — where do we start?",
  "Tell me about GataMail for my team.",
];

function ChatBudPage() {
  const load = useServerFn(loadBudThread);
  const send = useServerFn(sendBudMessage);

  const [sessionId, setSessionId] = useState<string | null>(null);
  const [conversationId, setConversationId] = useState<string | null>(null);
  const [messages, setMessages] = useState<BudMessage[]>([]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const endRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let id = window.localStorage.getItem(KEY);
    if (!id) {
      id = crypto.randomUUID();
      window.localStorage.setItem(KEY, id);
    }
    setSessionId(id);
    void load({ data: { sessionId: id } })
      .then((res) => {
        setConversationId(res.conversationId);
        setMessages(res.messages);
      })
      .catch(() => {});
  }, [load]);

  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, busy]);

  const submit = async (text: string) => {
    const value = text.trim();
    if (!value || !sessionId || busy) return;
    setInput("");
    setBusy(true);
    setMessages((prev) => [
      ...prev,
      {
        id: crypto.randomUUID(),
        role: "user",
        content: value,
        created_at: new Date().toISOString(),
      },
    ]);
    try {
      const res = await send({ data: { sessionId, conversationId, message: value } });
      setConversationId(res.conversationId);
      setMessages((prev) => [...prev, res.reply]);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "ChatBud could not reply.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="mx-auto max-w-4xl px-5 py-14">
      <p className="font-mono text-xs uppercase tracking-[0.2em] text-primary">Products</p>
      <h1 className="mt-3 text-4xl font-bold md:text-5xl">
        Chat<span className="text-gradient">Bud</span>
      </h1>
      <p className="mt-4 max-w-2xl text-muted-foreground">
        Your conversational companion for everything Gatavase. Ask anything — every message is saved
        to your thread so you can continue where you left off.
      </p>

      <div className="mt-9 overflow-hidden rounded-3xl border border-primary/25 bg-card/60 backdrop-blur">
        <div className="flex items-center gap-3 border-b border-border px-5 py-3">
          <span className="grid size-8 place-items-center rounded-full bg-primary/15 text-primary">
            <MessageCircle className="size-4" />
          </span>
          <div>
            <p className="text-sm font-semibold">ChatBud</p>
            <p className="text-[11px] text-muted-foreground">
              {busy ? "Typing…" : "Online · powered by Gatavase AI"}
            </p>
          </div>
        </div>

        <div className="max-h-[52vh] min-h-[320px] space-y-4 overflow-y-auto px-5 py-6">
          {messages.length === 0 && (
            <div className="space-y-4">
              <p className="text-sm text-muted-foreground">
                Hi! I&apos;m ChatBud. Pick a starter or type your own question.
              </p>
              <div className="flex flex-wrap gap-2">
                {STARTERS.map((s) => (
                  <button
                    key={s}
                    onClick={() => void submit(s)}
                    className="rounded-full border border-input px-3.5 py-1.5 text-xs hover:border-primary/50 hover:text-primary"
                  >
                    {s}
                  </button>
                ))}
              </div>
            </div>
          )}

          {messages.map((m) => (
            <div
              key={m.id}
              className={m.role === "user" ? "flex justify-end" : "flex justify-start"}
            >
              <div
                className={`max-w-[85%] whitespace-pre-wrap rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${
                  m.role === "user"
                    ? "bg-primary text-primary-foreground"
                    : "border border-border bg-background/70"
                }`}
              >
                {m.content}
              </div>
            </div>
          ))}
          {busy && (
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
              <Loader2 className="size-3.5 animate-spin" /> ChatBud is thinking…
            </div>
          )}
          <div ref={endRef} />
        </div>

        <form
          onSubmit={(e) => {
            e.preventDefault();
            void submit(input);
          }}
          className="flex items-center gap-2 border-t border-border px-4 py-3"
        >
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="Message ChatBud…"
            aria-label="Message ChatBud"
            className="flex-1 rounded-full border border-input bg-background px-4 py-2.5 text-sm"
          />
          <button
            type="submit"
            disabled={busy || !input.trim()}
            aria-label="Send message"
            className="grid size-10 place-items-center rounded-full bg-primary text-primary-foreground disabled:opacity-50"
          >
            <Send className="size-4" />
          </button>
        </form>
      </div>
    </div>
  );
}
