import { env } from "@code/env/web";
import { FlueProvider, useFlueAgent } from "@flue/react";
import { createFlueClient } from "@flue/sdk";
import { ArrowUp, Loader2, MessageSquare } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";

const STANDALONE_CHAT_ID = "zopu-standalone";

const StandaloneFlueProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const client = useMemo(
    () =>
      createFlueClient({
        baseUrl: env.VITE_ZOPU_SERVER_URL,
      }),
    []
  );
  return <FlueProvider client={client}>{children}</FlueProvider>;
};

const extractText = (parts: { type: string; text?: string }[]): string =>
  parts
    .filter((p) => p.type === "text" && p.text)
    .map((p) => p.text ?? "")
    .join("");

const ChatMessage = ({
  parts,
  role,
}: {
  parts: { type: string; text?: string }[];
  role: string;
}) => {
  const isUser = role === "user";
  return (
    <div
      className={`flex w-full gap-3 px-4 py-3 ${isUser ? "justify-end" : "justify-start"}`}
    >
      {!isUser && (
        <div className="mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-full bg-[#1a1a19] text-[#e8e8e6]">
          <MessageSquare className="size-3.5" />
        </div>
      )}
      <div
        className={`max-w-[78%] whitespace-pre-wrap rounded-2xl px-4 py-2.5 text-[15px] leading-relaxed ${
          isUser ? "bg-[#e8e8e6] text-[#0e0e0d]" : "bg-[#1a1a19] text-[#e8e8e6]"
        }`}
      >
        {extractText(parts) || <span className="text-[#888]">...</span>}
      </div>
    </div>
  );
};

const ChatContent = () => {
  const agent = useFlueAgent({
    id: STANDALONE_CHAT_ID,
    name: "zopu",
  });
  const [input, setInput] = useState("");
  const scrollRef = useRef<HTMLDivElement>(null);

  const hasMessages = agent.messages.length > 0;
  const isBusy = agent.status === "submitted" || agent.status === "streaming";

  useEffect(() => {
    const el = scrollRef.current;
    if (el) {
      el.scrollTop = el.scrollHeight;
    }
  }, [agent.messages, isBusy]);

  const submit = async () => {
    const message = input.trim();
    if (!message || isBusy) {
      return;
    }
    setInput("");
    await agent.sendMessage(message);
  };

  return (
    <div className="flex h-svh flex-col bg-[#0e0e0d]">
      <header className="flex items-center gap-2 border-b border-[#1f1f1e] px-4 py-3">
        <div className="flex size-7 items-center justify-center rounded-full bg-[#e8e8e6]">
          <span className="text-sm font-bold text-[#0e0e0d]">Z</span>
        </div>
        <div className="flex-1">
          <h1 className="text-[15px] font-semibold text-[#e8e8e6]">Zopu</h1>
          <p className="text-xs text-[#888]">
            {isBusy ? "working..." : "ready"}
          </p>
        </div>
      </header>

      <div className="min-h-0 flex-1 overflow-y-auto py-2" ref={scrollRef}>
        {!hasMessages && !agent.historyReady && (
          <div className="flex h-full items-center justify-center">
            <Loader2 className="size-5 animate-spin text-[#555]" />
          </div>
        )}
        {!hasMessages && agent.historyReady && (
          <div className="flex h-full flex-col items-center justify-center gap-4 px-8 text-center">
            <div className="flex size-12 items-center justify-center rounded-2xl bg-[#1a1a19]">
              <MessageSquare className="size-5 text-[#e8e8e6]" />
            </div>
            <div>
              <p className="text-[15px] font-medium text-[#e8e8e6]">
                Chat with Zopu
              </p>
              <p className="mt-1 text-sm text-[#888]">
                Ask about issues, trigger work, or check PR status.
              </p>
            </div>
            <div className="flex flex-wrap justify-center gap-2 pt-2">
              {[
                "List recent pull requests",
                "Create an issue for adding a settings page",
              ].map((suggestion) => (
                <button
                  className="rounded-full border border-[#2a2a29] bg-[#161615] px-3 py-1.5 text-xs text-[#aaa] transition hover:border-[#3a3a39] hover:text-[#e8e8e6]"
                  key={suggestion}
                  onClick={() => void agent.sendMessage(suggestion)}
                  type="button"
                >
                  {suggestion}
                </button>
              ))}
            </div>
          </div>
        )}
        {agent.messages.map((message) => (
          <ChatMessage
            key={message.id}
            parts={message.parts}
            role={message.role}
          />
        ))}
      </div>

      <div className="border-t border-[#1f1f1e] px-3 py-3">
        <div className="flex items-end gap-2 rounded-2xl border border-[#2a2a29] bg-[#161615] px-3 py-2">
          <textarea
            className="flex-1 resize-none bg-transparent text-[15px] text-[#e8e8e6] placeholder-[#666] outline-none"
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                void submit();
              }
            }}
            placeholder="Message Zopu..."
            rows={1}
            style={{ maxHeight: 120 }}
            value={input}
          />
          <button
            className={`flex size-8 shrink-0 items-center justify-center rounded-lg transition ${
              input.trim() && !isBusy
                ? "bg-[#e8e8e6] text-[#0e0e0d]"
                : "bg-[#2a2a29] text-[#555]"
            }`}
            disabled={!input.trim() || isBusy}
            onClick={() => void submit()}
            type="button"
          >
            {isBusy ? (
              <Loader2 className="size-4 animate-spin" />
            ) : (
              <ArrowUp className="size-4" />
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export const StandaloneChatPage = () => (
  <StandaloneFlueProvider>
    <ChatContent />
  </StandaloneFlueProvider>
);
