"use client";

import { useState, useRef, useEffect } from "react";

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

const SUGGESTIONS = ["Ce este Dialpilot?", "Cat costa?", "Cum il instalez?", "Pot face rezervari?"];

export default function DemoChat() {
  const [messages, setMessages] = useState<Message[]>([
    { role: "assistant", content: "Salut! Sunt Pilot, asistentul demo al Dialpilot. Intreaba-ma orice despre platforma sau testeaza-ma! 🚀" }
  ]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [limitReached, setLimitReached] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

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

  async function sendText(text: string) {
    if (!text.trim() || loading || limitReached) return;
    const newMessages: Message[] = [...messages, { role: "user", content: text }];
    setMessages([...newMessages, { role: "assistant", content: "" }]);
    setInput("");
    setLoading(true);

    try {
      const res = await fetch("/api/chat/demo", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: newMessages }),
      });

      if (res.status === 429) {
        setMessages([...newMessages, { role: "assistant", content: "Ai ajuns la limita demo! Creeaza un cont gratuit pentru a continua — dureaza 30 de secunde. 👇" }]);
        setLimitReached(true);
        setLoading(false);
        return;
      }

      if (!res.ok) {
        setMessages([...newMessages, { role: "assistant", content: "Ceva nu a mers. Incearca din nou!" }]);
        setLoading(false);
        return;
      }

      const reader = res.body!.getReader();
      const decoder = new TextDecoder();
      let accumulated = "";
      let buffer = "";
      let errorOccurred = false;

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        // Accumulate into buffer — prevents splitting a data line across two reads
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        // Keep the last (potentially incomplete) line in the buffer
        buffer = lines.pop() ?? "";
        for (const line of lines) {
          if (!line.startsWith("data: ")) continue;
          const data = line.slice(6).trim();
          if (data === "[DONE]") continue;
          try {
            const parsed = JSON.parse(data);
            if (parsed.text) {
              accumulated += parsed.text;
              setMessages([...newMessages, { role: "assistant", content: accumulated }]);
            }
            if (parsed.error) {
              errorOccurred = true;
              setMessages([...newMessages, { role: "assistant", content: "Ne pare rau, a aparut o eroare. Incearca din nou!" }]);
            }
          } catch {}
        }
      }

      if (!accumulated && !errorOccurred) {
        setMessages([...newMessages, { role: "assistant", content: "Ne pare rau, nu am putut genera un raspuns. Incearca din nou!" }]);
      }
    } catch {
      setMessages([...newMessages, { role: "assistant", content: "Eroare de conexiune. Incearca din nou." }]);
    }

    setLoading(false);
    inputRef.current?.focus();
  }

  return (
    <div className="flex flex-col h-[480px] bg-[#0d1117] border border-white/[0.08] rounded-2xl overflow-hidden shadow-2xl shadow-black/40">
      {/* Header */}
      <div className="flex items-center gap-3 px-4 py-3 bg-gradient-to-r from-indigo-600 to-violet-600 shrink-0">
        <div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center text-sm">🤖</div>
        <div>
          <p className="text-white font-bold text-sm">Pilot — Demo Dialpilot</p>
          <p className="text-white/70 text-xs flex items-center gap-1.5">
            <span className="w-1.5 h-1.5 bg-emerald-400 rounded-full inline-block" />
            Online acum
          </p>
        </div>
        <div className="ml-auto bg-white/20 text-white text-[10px] font-bold px-2.5 py-1 rounded-full">DEMO LIVE</div>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-4 space-y-3">
        {messages.map((msg, i) => {
          const isTyping = msg.role === "assistant" && msg.content === "" && loading && i === messages.length - 1;
          return (
            <div key={i} className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"} items-end gap-2`}>
              {msg.role === "assistant" && (
                <div className="w-6 h-6 bg-gradient-to-br from-indigo-500 to-violet-600 rounded-full flex items-center justify-center text-xs shrink-0">🤖</div>
              )}
              <div className={`max-w-[80%] px-3.5 py-2.5 rounded-2xl text-sm leading-relaxed ${
                msg.role === "user"
                  ? "bg-gradient-to-br from-indigo-600 to-violet-600 text-white rounded-br-sm"
                  : "bg-white/[0.07] text-slate-200 rounded-bl-sm"
              }`}>
                {isTyping ? (
                  <span className="flex gap-1 py-0.5">
                    {[0,1,2].map(d => (
                      <span key={d} className="w-1.5 h-1.5 bg-slate-400 rounded-full animate-bounce" style={{ animationDelay: `${d * 0.2}s` }} />
                    ))}
                  </span>
                ) : (
                  <span className="whitespace-pre-wrap">{msg.content}</span>
                )}
              </div>
            </div>
          );
        })}
        <div ref={bottomRef} />
      </div>

      {/* Quick suggestions — only when first message visible */}
      {messages.length <= 2 && !loading && (
        <div className="px-4 pb-2 flex flex-wrap gap-2">
          {SUGGESTIONS.map(s => (
            <button key={s} onClick={() => sendText(s)}
              className="text-xs border border-indigo-500/30 text-indigo-300 hover:bg-indigo-500/15 px-3 py-1.5 rounded-full transition-colors">
              {s}
            </button>
          ))}
        </div>
      )}

      {/* Input */}
      {limitReached ? (
        <div className="p-4 border-t border-white/[0.06] text-center">
          <p className="text-xs text-slate-500 mb-2">Limita demo atinsa — creeaza cont gratuit pentru mai mult</p>
          <a href="/register" className="inline-block bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 text-white text-sm font-bold px-5 py-2 rounded-xl transition-all">
            Incepe gratuit →
          </a>
        </div>
      ) : (
        <form onSubmit={e => { e.preventDefault(); sendText(input); }}
          className="flex gap-2 p-3 border-t border-white/[0.06] bg-white/[0.02] shrink-0">
          <input ref={inputRef} value={input} onChange={e => setInput(e.target.value)} disabled={loading}
            placeholder="Scrie o intrebare..."
            className="flex-1 bg-white/[0.06] border border-white/[0.1] rounded-xl px-3.5 py-2 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:ring-1 focus:ring-indigo-500/50" />
          <button type="submit" disabled={!input.trim() || loading}
            className="w-9 h-9 bg-gradient-to-br from-indigo-600 to-violet-600 disabled:opacity-30 rounded-xl flex items-center justify-center text-white text-sm transition-all hover:scale-105">
            ➤
          </button>
        </form>
      )}
    </div>
  );
}
