"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
  Send,
  Loader2,
  User,
  RotateCcw,
  FileText,
  CheckCircle2,
  ChevronDown,
  ChevronUp,
} from "lucide-react";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

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

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

// ---------------------------------------------------------------------------
// Atlas avatar — distinct from orchestrator
// ---------------------------------------------------------------------------

function AtlasAvatar() {
  return (
    <div className="w-7 h-7 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 flex items-center justify-center text-white text-xs font-bold shrink-0 shadow-sm">
      A
    </div>
  );
}

// ---------------------------------------------------------------------------
// PRD preview panel
// ---------------------------------------------------------------------------

function PrdPanel({ content }: { content: string }) {
  const [expanded, setExpanded] = useState(false);
  const preview = content.split("\n").slice(0, 6).join("\n");

  return (
    <div className="mt-4 border border-violet-200 dark:border-violet-800 rounded-xl overflow-hidden bg-violet-50/50 dark:bg-violet-950/20">
      <div className="flex items-center gap-2 px-4 py-3 bg-violet-100/60 dark:bg-violet-900/30">
        <CheckCircle2 className="w-4 h-4 text-violet-600 dark:text-violet-400" />
        <span className="text-sm font-semibold text-violet-700 dark:text-violet-300">
          PRD Generated
        </span>
        <span className="text-xs text-muted-foreground ml-auto">
          Ready for architecture phase
        </span>
        <Button
          variant="ghost"
          size="sm"
          className="h-6 px-2 text-xs text-violet-600"
          onClick={() => setExpanded(!expanded)}
        >
          {expanded ? (
            <ChevronUp className="w-3 h-3" />
          ) : (
            <ChevronDown className="w-3 h-3" />
          )}
        </Button>
      </div>
      <div className="px-4 py-3">
        <pre className={`text-xs text-muted-foreground whitespace-pre-wrap font-mono leading-relaxed ${expanded ? "" : "line-clamp-4"}`}>
          {expanded ? content : preview}
        </pre>
        {!expanded && (
          <button
            onClick={() => setExpanded(true)}
            className="text-xs text-violet-600 hover:underline mt-1"
          >
            View full PRD
          </button>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------

export function AtlasChat({ projectId, projectName, initialMessage }: AtlasChatProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [prdContent, setPrdContent] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [started, setStarted] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Auto-scroll to latest message
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, loading]);

  // Kick off Atlas with its opening message on first load
  useEffect(() => {
    if (started) return;
    setStarted(true);
    sendMessage(
      initialMessage ||
        `Hey — I'm starting a new project called "${projectName || "my project"}". I'd love your help defining what we're building.`
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const sendMessage = useCallback(
    async (text: string) => {
      if (!text.trim() || loading) return;
      setError(null);

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

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

        const data = await res.json();

        if (!res.ok) {
          setError(data.error || "Something went wrong. Please try again.");
          setMessages((prev) => prev.slice(0, -1));
          return;
        }

        const assistantMsg: Message = {
          role: "assistant",
          content: data.reply || "...",
        };
        setMessages((prev) => [...prev, assistantMsg]);

        if (data.prdContent) {
          setPrdContent(data.prdContent);
        }
      } catch {
        setError("Couldn't reach Atlas. Check your connection and try again.");
        setMessages((prev) => prev.slice(0, -1));
      } finally {
        setLoading(false);
        setTimeout(() => textareaRef.current?.focus(), 50);
      }
    },
    [loading, projectId]
  );

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

  const handleReset = async () => {
    if (!confirm("Start the discovery conversation over from scratch?")) return;
    await fetch(`/api/projects/${projectId}/atlas-chat`, { method: "DELETE" });
    setMessages([]);
    setPrdContent(null);
    setStarted(false);
    setError(null);
  };

  return (
    <div className="flex flex-col rounded-2xl border border-border/60 bg-card shadow-sm overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between px-5 py-3.5 border-b border-border/60 bg-gradient-to-r from-violet-50/80 to-indigo-50/50 dark:from-violet-950/30 dark:to-indigo-950/20">
        <div className="flex items-center gap-3">
          <AtlasAvatar />
          <div>
            <p className="text-sm font-semibold text-foreground">Atlas</p>
            <p className="text-xs text-muted-foreground">Product Requirements</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {prdContent && (
            <div className="flex items-center gap-1.5 text-xs text-violet-600 dark:text-violet-400 bg-violet-100 dark:bg-violet-900/40 px-2.5 py-1 rounded-full">
              <FileText className="w-3 h-3" />
              PRD ready
            </div>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={handleReset}
            className="h-7 w-7 p-0 text-muted-foreground hover:text-foreground"
            title="Start over"
          >
            <RotateCcw className="w-3.5 h-3.5" />
          </Button>
        </div>
      </div>

      {/* Messages */}
      <ScrollArea className="flex-1 max-h-[500px]">
        <div className="px-5 py-4 space-y-5">
          {messages.map((msg, i) => (
            <div
              key={i}
              className={`flex gap-3 ${msg.role === "user" ? "justify-end" : "justify-start"}`}
            >
              {msg.role === "assistant" && <AtlasAvatar />}

              <div
                className={`max-w-[82%] ${
                  msg.role === "user"
                    ? "bg-violet-600 text-white rounded-2xl rounded-tr-sm px-4 py-2.5"
                    : "bg-muted/60 rounded-2xl rounded-tl-sm px-4 py-3"
                }`}
              >
                <p className="text-sm leading-relaxed whitespace-pre-wrap">
                  {msg.content}
                </p>
              </div>

              {msg.role === "user" && (
                <div className="w-7 h-7 rounded-full bg-muted flex items-center justify-center shrink-0">
                  <User className="w-3.5 h-3.5 text-muted-foreground" />
                </div>
              )}
            </div>
          ))}

          {/* Typing indicator */}
          {loading && (
            <div className="flex gap-3 justify-start">
              <AtlasAvatar />
              <div className="bg-muted/60 rounded-2xl rounded-tl-sm px-4 py-3">
                <div className="flex gap-1.5 items-center h-4">
                  <span className="w-1.5 h-1.5 bg-violet-400 rounded-full animate-bounce [animation-delay:0ms]" />
                  <span className="w-1.5 h-1.5 bg-violet-400 rounded-full animate-bounce [animation-delay:150ms]" />
                  <span className="w-1.5 h-1.5 bg-violet-400 rounded-full animate-bounce [animation-delay:300ms]" />
                </div>
              </div>
            </div>
          )}

          {/* Error */}
          {error && (
            <div className="text-xs text-destructive bg-destructive/10 rounded-lg px-3 py-2">
              {error}
            </div>
          )}

          {/* PRD panel */}
          {prdContent && <PrdPanel content={prdContent} />}

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

      {/* Input */}
      <div className="px-4 py-3 border-t border-border/60 bg-muted/20">
        {prdContent ? (
          <p className="text-xs text-center text-muted-foreground py-1">
            PRD complete — the platform is now architecting your solution.
          </p>
        ) : (
          <div className="flex gap-2 items-end">
            <Textarea
              ref={textareaRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="Reply to Atlas…"
              rows={1}
              className="resize-none min-h-[40px] max-h-[120px] text-sm rounded-xl border-border/60 focus-visible:ring-violet-500/30 bg-background"
              style={{ overflow: "hidden" }}
              onInput={(e) => {
                const t = e.currentTarget;
                t.style.height = "auto";
                t.style.height = Math.min(t.scrollHeight, 120) + "px";
              }}
            />
            <Button
              onClick={() => sendMessage(input)}
              disabled={!input.trim() || loading}
              size="sm"
              className="h-10 w-10 p-0 rounded-xl bg-violet-600 hover:bg-violet-700 text-white shrink-0"
            >
              {loading ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Send className="w-4 h-4" />
              )}
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
