"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import { useSession } from "next-auth/react";

interface ChatMessage {
  role: "user" | "assistant";
  content: string;
}

interface AtlasChatProps {
  projectId: string;
  projectName?: string;
}

// ---------------------------------------------------------------------------
// Markdown-lite renderer — handles **bold**, newlines, numbered/bullet lists
// ---------------------------------------------------------------------------
function renderContent(text: string | null | undefined) {
  if (!text) return null;
  return text.split("\n").map((line, i) => {
    const parts = line.split(/(\*\*.*?\*\*)/g).map((seg, j) =>
      seg.startsWith("**") && seg.endsWith("**")
        ? <strong key={j} style={{ fontWeight: 600, color: "#1a1a1a" }}>{seg.slice(2, -2)}</strong>
        : <span key={j}>{seg}</span>
    );
    return <div key={i} style={{ minHeight: line.length ? undefined : "0.75em" }}>{parts}</div>;
  });
}

// ---------------------------------------------------------------------------
// Message row
// ---------------------------------------------------------------------------
function MessageRow({ msg, userInitial }: { msg: ChatMessage; userInitial: string }) {
  const isAtlas = msg.role === "assistant";
  return (
    <div style={{ display: "flex", gap: 12, marginBottom: 22, animation: "enter 0.3s ease both" }}>
      {/* Avatar */}
      <div style={{
        width: 28, height: 28, borderRadius: 7, flexShrink: 0, marginTop: 2,
        background: isAtlas ? "#1a1a1a" : "#e8e4dc",
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: "0.68rem", fontWeight: 700,
        color: isAtlas ? "#fff" : "#8a8478",
        fontFamily: isAtlas ? "Newsreader, serif" : "Outfit, sans-serif",
      }}>
        {isAtlas ? "A" : userInitial}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        {/* Label */}
        <div style={{
          fontSize: "0.68rem", fontWeight: 600, color: "#a09a90",
          marginBottom: 5, textTransform: "uppercase", letterSpacing: "0.04em",
          fontFamily: "Outfit, sans-serif",
        }}>
          {isAtlas ? "Atlas" : "You"}
        </div>
        {/* Content */}
        <div style={{
          fontSize: "0.88rem", color: "#2a2824", lineHeight: 1.72,
          fontFamily: "Outfit, sans-serif",
          whiteSpace: isAtlas ? "normal" : "pre-wrap",
        }}>
          {renderContent(msg.content)}
        </div>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Typing indicator
// ---------------------------------------------------------------------------
function TypingIndicator() {
  return (
    <div style={{ display: "flex", gap: 12, marginBottom: 22, animation: "enter 0.2s ease" }}>
      <div style={{
        width: 28, height: 28, borderRadius: 7, flexShrink: 0, marginTop: 2,
        background: "#1a1a1a", display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: "0.68rem", fontWeight: 700, color: "#fff", fontFamily: "Newsreader, serif",
      }}>A</div>
      <div style={{ display: "flex", gap: 5, paddingTop: 10 }}>
        {[0, 1, 2].map(d => (
          <div key={d} style={{
            width: 5, height: 5, borderRadius: "50%", background: "#b5b0a6",
            animation: `blink 1s ease ${d * 0.15}s infinite`,
          }} />
        ))}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------
export function AtlasChat({ projectId }: AtlasChatProps) {
  const { data: session } = useSession();
  const userInitial =
    session?.user?.name?.[0]?.toUpperCase() ??
    session?.user?.email?.[0]?.toUpperCase() ??
    "Y";

  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState("");
  const [isStreaming, setIsStreaming] = useState(false);
  const [historyLoaded, setHistoryLoaded] = useState(false);
  const initTriggered = useRef(false);
  const endRef = useRef<HTMLDivElement>(null);

  // Scroll to bottom whenever messages change
  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, isStreaming]);

  // Send a message to Atlas — optionally hidden from UI (for init trigger)
  const sendToAtlas = useCallback(async (text: string, hideUserMsg = false) => {
    if (!hideUserMsg) {
      setMessages(prev => [...prev, { role: "user", content: text }]);
    }
    setIsStreaming(true);

    try {
      const res = await fetch(`/api/projects/${projectId}/atlas-chat`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: text }),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.error || "Atlas is unavailable. Please try again.");
      }

      const data = await res.json();

      // alreadyStarted means the init was called but history already exists — ignore
      if (data.alreadyStarted) return;

      if (data.reply) {
        setMessages(prev => [...prev, { role: "assistant", content: data.reply }]);
      }
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Something went wrong.";
      setMessages(prev => [...prev, { role: "assistant", content: msg }]);
    } finally {
      setIsStreaming(false);
    }
  }, [projectId]);

  // On mount: load stored history; if empty, trigger Atlas greeting exactly once
  useEffect(() => {
    let cancelled = false; // guard against unmount during fetch

    fetch(`/api/projects/${projectId}/atlas-chat`)
      .then(r => r.json())
      .then((data: { messages: ChatMessage[] }) => {
        if (cancelled) return;
        const stored = data.messages ?? [];
        setMessages(stored);
        setHistoryLoaded(true);

        // Only greet if there is genuinely no history and we haven't triggered yet
        if (stored.length === 0 && !initTriggered.current) {
          initTriggered.current = true;
          sendToAtlas("__atlas_init__", true);
        }
      })
      .catch(() => {
        if (cancelled) return;
        setHistoryLoaded(true);
      });

    return () => { cancelled = true; };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [projectId]);

  const handleReset = async () => {
    if (!confirm("Clear this conversation and start fresh?")) return;
    try {
      await fetch(`/api/projects/${projectId}/atlas-chat`, { method: "DELETE" });
      setMessages([]);
      setHistoryLoaded(false);
      initTriggered.current = false;
      // Trigger fresh greeting
      setTimeout(() => {
        initTriggered.current = true;
        sendToAtlas("__atlas_init__", true);
      }, 100);
    } catch {
      // swallow
    }
  };

  const handleSend = () => {
    const text = input.trim();
    if (!text || isStreaming) return;
    setInput("");
    sendToAtlas(text, false);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const visibleMessages = messages.filter(msg => msg.content);
  const isEmpty = visibleMessages.length === 0 && !isStreaming;

  return (
    <div style={{
      display: "flex", flexDirection: "column", height: "100%",
      background: "#f6f4f0", fontFamily: "Outfit, sans-serif",
    }}>
      <style>{`
        @keyframes blink { 0%,100%{opacity:.2} 50%{opacity:.8} }
        @keyframes enter { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:translateY(0); } }
      `}</style>

      {/* Empty state */}
      {isEmpty && (
        <div style={{
          flex: 1, display: "flex", flexDirection: "column",
          alignItems: "center", justifyContent: "center",
          gap: 12, padding: "40px 32px",
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 11, background: "#1a1a1a",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontFamily: "Newsreader, serif", fontSize: "1.2rem", fontWeight: 500, color: "#fff",
            animation: "breathe 2.5s ease infinite",
          }}>A</div>
          <style>{`@keyframes breathe { 0%,100%{transform:scale(1)} 50%{transform:scale(1.08)} }`}</style>
          <div style={{ textAlign: "center" }}>
            <p style={{ fontSize: "0.88rem", fontWeight: 600, color: "#1a1a1a", marginBottom: 4 }}>Atlas</p>
            <p style={{ fontSize: "0.78rem", color: "#a09a90", maxWidth: 260, lineHeight: 1.5 }}>
              Your product strategist. Let&apos;s define what you&apos;re building.
            </p>
          </div>
        </div>
      )}

      {/* Messages */}
      {!isEmpty && (
        <div style={{ flex: 1, overflowY: "auto", padding: "28px 32px", position: "relative" }}>
          {/* Reset button — top right, only visible on hover of the area */}
          <button
            onClick={handleReset}
            title="Reset conversation"
            style={{
              position: "absolute", top: 12, right: 16,
              background: "none", border: "none", cursor: "pointer",
              fontSize: "0.68rem", color: "#d0ccc4", fontFamily: "Outfit, sans-serif",
              padding: "3px 7px", borderRadius: 4, transition: "color 0.12s",
            }}
            onMouseEnter={e => (e.currentTarget.style.color = "#8a8478")}
            onMouseLeave={e => (e.currentTarget.style.color = "#d0ccc4")}
          >
            Reset
          </button>
          {visibleMessages.map((msg, i) => (
            <MessageRow key={i} msg={msg} userInitial={userInitial} />
          ))}
          {isStreaming && <TypingIndicator />}
          <div ref={endRef} />
        </div>
      )}

      {/* Loading history state */}
      {isEmpty && isStreaming && (
        <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <TypingIndicator />
        </div>
      )}

      {/* Input bar */}
      <div style={{ padding: "14px 32px 22px", flexShrink: 0 }}>
        <div style={{
          display: "flex", gap: 8, padding: "5px 5px 5px 16px",
          background: "#fff", border: "1px solid #e0dcd4", borderRadius: 10,
          alignItems: "center", boxShadow: "0 1px 4px #1a1a1a06",
        }}>
          <textarea
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Describe your thinking..."
            rows={1}
            disabled={isStreaming}
            style={{
              flex: 1, border: "none", background: "none",
              fontSize: "0.86rem", fontFamily: "Outfit, sans-serif",
              color: "#1a1a1a", padding: "8px 0",
              resize: "none", outline: "none",
              minHeight: 24, maxHeight: 120,
            }}
          />
          {isStreaming ? (
            <button
              onClick={() => setIsStreaming(false)}
              style={{
                padding: "9px 16px", borderRadius: 7, border: "none",
                background: "#eae6de", color: "#8a8478",
                fontSize: "0.78rem", fontWeight: 600, fontFamily: "Outfit, sans-serif",
                cursor: "pointer", flexShrink: 0,
                display: "flex", alignItems: "center", gap: 6,
              }}
            >
              <span style={{ width: 10, height: 10, background: "#8a8478", borderRadius: 2, display: "inline-block" }} />
              Stop
            </button>
          ) : (
            <button
              onClick={handleSend}
              disabled={!input.trim()}
              style={{
                padding: "9px 16px", borderRadius: 7, border: "none",
                background: input.trim() ? "#1a1a1a" : "#eae6de",
                color: input.trim() ? "#fff" : "#b5b0a6",
                fontSize: "0.78rem", fontWeight: 600, fontFamily: "Outfit, sans-serif",
                cursor: input.trim() ? "pointer" : "default",
                flexShrink: 0, transition: "all 0.15s",
              }}
              onMouseEnter={e => { if (input.trim()) (e.currentTarget.style.opacity = "0.8"); }}
              onMouseLeave={e => { (e.currentTarget.style.opacity = "1"); }}
            >
              Send
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
