"use client";

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

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

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

// ---------------------------------------------------------------------------
// Markers — Atlas appends these at end of messages to signal UI actions
// ---------------------------------------------------------------------------

const PHASE_MARKER_RE = /\[\[PHASE_COMPLETE:(.*?)\]\]/s;
const NEXT_STEP_RE = /\[\[NEXT_STEP:(.*?)\]\]/s;

interface PhasePayload {
  phase: string;
  title: string;
  summary: string;
  data: Record<string, unknown>;
}

interface NextStepPayload {
  action: string;
  label: string;
}

function extractMarkers(text: string): {
  clean: string;
  phase: PhasePayload | null;
  nextStep: NextStepPayload | null;
} {
  let clean = text;
  let phase: PhasePayload | null = null;
  let nextStep: NextStepPayload | null = null;

  const phaseMatch = clean.match(PHASE_MARKER_RE);
  if (phaseMatch) {
    try { phase = JSON.parse(phaseMatch[1]); } catch { /* ignore */ }
    clean = clean.replace(PHASE_MARKER_RE, "").trimEnd();
  }

  const nextMatch = clean.match(NEXT_STEP_RE);
  if (nextMatch) {
    try { nextStep = JSON.parse(nextMatch[1]); } catch { /* ignore */ }
    clean = clean.replace(NEXT_STEP_RE, "").trimEnd();
  }

  return { clean, phase, nextStep };
}

// ---------------------------------------------------------------------------
// 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, projectId, workspace,
}: {
  msg: ChatMessage;
  userInitial: string;
  projectId: string;
  workspace: string;
}) {
  const isAtlas = msg.role === "assistant";
  const { clean, phase, nextStep } = isAtlas
    ? extractMarkers(msg.content ?? "")
    : { clean: msg.content ?? "", phase: null, nextStep: null };

  // Phase save state
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);

  // Architecture generation state
  const [archState, setArchState] = useState<"idle" | "loading" | "done" | "error">("idle");
  const [archError, setArchError] = useState<string | null>(null);

  const handleSavePhase = async () => {
    if (!phase || saved || saving) return;
    setSaving(true);
    try {
      await fetch(`/api/projects/${projectId}/save-phase`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(phase),
      });
      setSaved(true);
    } catch { /* swallow — user can retry */ } finally {
      setSaving(false);
    }
  };

  const handleGenerateArchitecture = async () => {
    if (archState !== "idle") return;
    setArchState("loading");
    setArchError(null);
    try {
      const res = await fetch(`/api/projects/${projectId}/architecture`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({}),
      });
      const d = await res.json();
      if (!res.ok) throw new Error(d.error || "Generation failed");
      setArchState("done");
    } catch (e) {
      setArchError(e instanceof Error ? e.message : "Something went wrong");
      setArchState("error");
    }
  };

  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(clean)}
        </div>

        {/* Phase save button */}
        {phase && (
          <div style={{ marginTop: 14 }}>
            <button
              onClick={handleSavePhase}
              disabled={saved || saving}
              style={{
                display: "inline-flex", alignItems: "center", gap: 7,
                padding: "8px 16px", borderRadius: 8,
                background: saved ? "#e8f5e9" : "#1a1a1a",
                color: saved ? "#2e7d32" : "#fff",
                border: saved ? "1px solid #a5d6a7" : "none",
                fontSize: "0.78rem", fontWeight: 600,
                fontFamily: "Outfit, sans-serif",
                cursor: saved || saving ? "default" : "pointer",
                transition: "all 0.15s",
                opacity: saving ? 0.7 : 1,
              }}
            >
              {saved ? "✓ Phase saved" : saving ? "Saving…" : `Save phase — ${phase.title}`}
            </button>
            {!saved && (
              <div style={{
                marginTop: 6, fontSize: "0.72rem", color: "#a09a90",
                fontFamily: "Outfit, sans-serif", lineHeight: 1.4,
              }}>
                {phase.summary}
              </div>
            )}
          </div>
        )}

        {/* Next step — architecture generation */}
        {nextStep?.action === "generate_architecture" && (
          <div style={{
            marginTop: 16,
            padding: "16px 18px",
            background: "#fff",
            border: "1px solid #e8e4dc",
            borderRadius: 10,
            borderLeft: "3px solid #1a1a1a",
          }}>
            {archState === "done" ? (
              <div>
                <div style={{ fontSize: "0.82rem", fontWeight: 600, color: "#2e7d32", marginBottom: 6 }}>
                  ✓ Architecture generated
                </div>
                <p style={{ fontSize: "0.76rem", color: "#6b6560", margin: "0 0 12px", lineHeight: 1.5 }}>
                  Review the recommended apps, services, and infrastructure — then confirm when you&apos;re ready.
                </p>
                <Link
                  href={`/${workspace}/project/${projectId}/build`}
                  style={{
                    display: "inline-block", padding: "8px 16px", borderRadius: 7,
                    background: "#1a1a1a", color: "#fff",
                    fontSize: "0.76rem", fontWeight: 600,
                    fontFamily: "Outfit, sans-serif", textDecoration: "none",
                  }}
                >
                  Review architecture →
                </Link>
              </div>
            ) : archState === "error" ? (
              <div>
                <div style={{ fontSize: "0.78rem", color: "#c62828", marginBottom: 8 }}>
                  ⚠ {archError}
                </div>
                <button
                  onClick={() => { setArchState("idle"); setArchError(null); }}
                  style={{
                    padding: "7px 14px", borderRadius: 6, border: "1px solid #e0dcd4",
                    background: "none", fontSize: "0.74rem", color: "#6b6560",
                    fontFamily: "Outfit, sans-serif", cursor: "pointer",
                  }}
                >
                  Try again
                </button>
              </div>
            ) : (
              <div>
                <div style={{ fontSize: "0.82rem", fontWeight: 600, color: "#1a1a1a", marginBottom: 5 }}>
                  Next: Technical architecture
                </div>
                <p style={{ fontSize: "0.76rem", color: "#6b6560", margin: "0 0 14px", lineHeight: 1.55 }}>
                  The AI will read your PRD and recommend the apps, services, and infrastructure your product needs. Takes about 30 seconds.
                </p>
                <button
                  onClick={handleGenerateArchitecture}
                  disabled={archState === "loading"}
                  style={{
                    display: "inline-flex", alignItems: "center", gap: 8,
                    padding: "9px 18px", borderRadius: 8, border: "none",
                    background: archState === "loading" ? "#8a8478" : "#1a1a1a",
                    color: "#fff", fontSize: "0.78rem", fontWeight: 600,
                    fontFamily: "Outfit, sans-serif",
                    cursor: archState === "loading" ? "default" : "pointer",
                    transition: "background 0.15s",
                  }}
                >
                  {archState === "loading" && (
                    <span style={{
                      width: 12, height: 12, borderRadius: "50%",
                      border: "2px solid #ffffff40", borderTopColor: "#fff",
                      animation: "spin 0.7s linear infinite", display: "inline-block",
                    }} />
                  )}
                  {archState === "loading" ? "Analysing PRD…" : nextStep.label}
                </button>
              </div>
            )}
          </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 params = useParams();
  const workspace = (params?.workspace as string) ?? "";
  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); } }
        @keyframes spin { to { transform:rotate(360deg); } }
      `}</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} projectId={projectId} workspace={workspace} />
          ))}
          {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 max(22px, env(safe-area-inset-bottom))", 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>
  );
}
