"use client";

import { useState, useRef, useEffect } from "react";
import { RotateCcw, Send } from "lucide-react";

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

const TYPING_STYLE = `
@keyframes dp-bounce {
  0%,60%,100%{transform:translateY(0);opacity:.4}
  30%{transform:translateY(-5px);opacity:1}
}
.dp-dot{width:6px;height:6px;border-radius:50%;background:#6366f1;display:inline-block;margin:0 2px;animation:dp-bounce 1.2s infinite}
.dp-dot:nth-child(2){animation-delay:.2s}
.dp-dot:nth-child(3){animation-delay:.4s}
`;

export function DashboardChatWidget({
  botId, botName, welcomeMessage, primaryColor,
}: { botId: string; botName: string; welcomeMessage: string; primaryColor: string }) {
  const [messages, setMessages] = useState<Message[]>([{ role: "assistant", content: welcomeMessage }]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

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

  function reset() {
    setMessages([{ role: "assistant", content: welcomeMessage }]);
    setInput("");
    setLoading(false);
  }

  async function send(e: React.FormEvent) {
    e.preventDefault();
    const text = input.trim();
    if (!text || loading) return;

    const newMsgs: Message[] = [...messages, { role: "user", content: text }];
    setMessages([...newMsgs, { role: "assistant", content: "" }]);
    setInput("");
    setLoading(true);

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

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        setMessages([...newMsgs, { role: "assistant", content: err.error ?? "Eroare la generare." }]);
        setLoading(false);
        return;
      }

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

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        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([...newMsgs, { role: "assistant", content: accumulated }]); }
            if (parsed.error) setMessages([...newMsgs, { role: "assistant", content: parsed.error }]);
          } catch {}
        }
      }
    } catch {
      setMessages([...newMsgs, { role: "assistant", content: "Eroare de conexiune." }]);
    }
    setLoading(false);
    inputRef.current?.focus();
  }

  return (
    <div className="flex flex-col h-full rounded-2xl border border-white/[0.08] overflow-hidden" style={{ background: "var(--bg-card)" }}>
      <style>{TYPING_STYLE}</style>

      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 shrink-0 border-b border-white/[0.07]"
        style={{ background: `linear-gradient(135deg, ${primaryColor}22, ${primaryColor}11)` }}>
        <div className="flex items-center gap-2.5">
          <div className="w-9 h-9 rounded-xl flex items-center justify-center text-base border border-white/10"
            style={{ backgroundColor: primaryColor + "30" }}>🤖</div>
          <div>
            <p className="text-sm font-bold text-white">{botName}</p>
            <div className="flex items-center gap-1.5">
              <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
              <p className="text-xs text-slate-400">Mod testare activ</p>
            </div>
          </div>
        </div>
        <button onClick={reset}
          className="flex items-center gap-1.5 text-xs text-slate-400 hover:text-white border border-white/[0.08] hover:border-white/20 px-3 py-1.5 rounded-lg transition-all">
          <RotateCcw className="w-3 h-3" />
          Reseteaza
        </button>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.map((msg, i) => {
          const isTyping = msg.role === "assistant" && msg.content === "" && loading && i === messages.length - 1;
          return (
            <div key={i} className={`flex items-end gap-2.5 ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
              {msg.role === "assistant" && (
                <div className="w-7 h-7 rounded-xl shrink-0 flex items-center justify-center text-xs border border-white/10"
                  style={{ backgroundColor: primaryColor + "30" }}>🤖</div>
              )}
              <div className={`max-w-[78%] px-4 py-2.5 text-sm rounded-2xl leading-relaxed ${
                msg.role === "user"
                  ? "text-white rounded-br-sm"
                  : "rounded-bl-sm border border-white/[0.07] text-slate-200"
              }`} style={msg.role === "user"
                ? { backgroundColor: primaryColor }
                : { background: "rgba(255,255,255,0.04)" }
              }>
                {isTyping ? (
                  <span><span className="dp-dot"/><span className="dp-dot"/><span className="dp-dot"/></span>
                ) : (
                  <span style={{ whiteSpace: "pre-wrap" }}>{msg.content}</span>
                )}
              </div>
              {msg.role === "user" && (
                <div className="w-7 h-7 rounded-xl shrink-0 flex items-center justify-center text-xs font-bold text-white bg-slate-600 border border-white/10">
                  Tu
                </div>
              )}
            </div>
          );
        })}
        <div ref={bottomRef} />
      </div>

      {/* Input */}
      <form onSubmit={send} className="flex gap-2 p-3 border-t border-white/[0.07] shrink-0"
        style={{ background: "rgba(255,255,255,0.02)" }}>
        <input
          ref={inputRef}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          disabled={loading}
          placeholder="Scrie un mesaj de test..."
          className="flex-1 rounded-xl px-4 py-2.5 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:ring-2 focus:ring-indigo-500/40 disabled:opacity-50 border border-white/[0.08] focus:border-indigo-500/40 transition-all"
          style={{ background: "rgba(255,255,255,0.04)" }}
          autoFocus
        />
        <button
          type="submit"
          disabled={!input.trim() || loading}
          className="w-10 h-10 rounded-xl flex items-center justify-center text-white shrink-0 disabled:opacity-30 transition-all hover:opacity-90"
          style={{ backgroundColor: primaryColor }}
        >
          <Send className="w-4 h-4" />
        </button>
      </form>
    </div>
  );
}
