"use client";

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

interface Message { role: "user" | "assistant"; content: string }
interface LeadData { name?: string; email?: string; phone?: string }

const BUTTONS_TAG_RE = /\[BUTOANE:\s*([^\]]+)\]/i;

function parseButtons(content: string): { text: string; buttons: string[] } {
  const m = content.match(BUTTONS_TAG_RE);
  if (!m) return { text: content, buttons: [] };
  const buttons = m[1].split("|").map(b => b.trim()).filter(Boolean);
  return { text: content.replace(BUTTONS_TAG_RE, "").trim(), buttons };
}

const TYPING_STYLE = `
@keyframes dp-bounce{0%,60%,100%{transform:translateY(0);opacity:.35}30%{transform:translateY(-5px);opacity:1}}
.dp-dot{width:7px;height:7px;border-radius:50%;background:#94a3b8;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}
@keyframes dp-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
.dp-msg{animation:dp-in .18s ease-out}
`;

function generateSessionId() { return Math.random().toString(36).slice(2) + Date.now().toString(36); }

export function ChatWidget({
  botId, botName, welcomeMessage, primaryColor,
  leadCaptureEnabled = false, leadCaptureTitle = "Inainte sa incepem...", leadCaptureFields = "name,email",
  showBranding = true,
}: {
  botId: string; botName: string; welcomeMessage: string; primaryColor: string;
  leadCaptureEnabled?: boolean; leadCaptureTitle?: string; leadCaptureFields?: string;
  showBranding?: boolean;
}) {
  const [messages, setMessages] = useState<Message[]>([{ role: "assistant", content: welcomeMessage }]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [leadSubmitted, setLeadSubmitted] = useState(!leadCaptureEnabled);
  const [leadData, setLeadData] = useState<LeadData>({});
  const [leadErrors, setLeadErrors] = useState<string>("");
  const sessionId = useRef(generateSessionId());
  const bottomRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const fields = leadCaptureFields.split(",").map(f => f.trim());

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

  function handleLeadSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (fields.includes("name") && !leadData.name?.trim()) { setLeadErrors("Va rugam introduceti numele."); return; }
    if (fields.includes("email") && !leadData.email?.trim()) { setLeadErrors("Va rugam introduceti emailul."); return; }
    setLeadErrors("");
    setLeadSubmitted(true);
    setTimeout(() => inputRef.current?.focus(), 100);
  }

  async function sendText(text: string) {
    if (!text || loading) return;

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

    try {
      const res = await fetch(`/api/chat/${botId}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          messages: newMessages.map((m) => ({ role: m.role, content: m.content })),
          sessionId: sessionId.current,
          lead: leadCaptureEnabled ? leadData : undefined,
        }),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        setMessages([...newMessages, { role: "assistant", content: err.error ?? "A aparut o eroare. Te rog incearca din nou." }]);
        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([...newMessages, { role: "assistant", content: accumulated }]); }
            if (parsed.error) setMessages([...newMessages, { role: "assistant", content: parsed.error }]);
          } catch {}
        }
      }
    } catch {
      setMessages([...newMessages, { role: "assistant", content: "A aparut o eroare de conexiune." }]);
    }

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

  async function sendMessage(e: React.FormEvent) {
    e.preventDefault();
    await sendText(input.trim());
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100vh", fontFamily: "system-ui,-apple-system,sans-serif", fontSize: "14px", backgroundColor: "#fff", margin: 0, padding: 0 }}>
      <style>{TYPING_STYLE}</style>

      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", gap: "12px", padding: "12px 16px", backgroundColor: primaryColor, flexShrink: 0 }}>
        <div style={{ width: "34px", height: "34px", borderRadius: "50%", backgroundColor: "rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "17px" }}>🤖</div>
        <div>
          <div style={{ fontWeight: 700, color: "#fff", fontSize: "14px" }}>{botName}</div>
          <div style={{ color: "rgba(255,255,255,0.75)", fontSize: "11px", display: "flex", alignItems: "center", gap: "4px" }}>
            <span style={{ width: "6px", height: "6px", borderRadius: "50%", backgroundColor: "#4ade80", display: "inline-block" }} />
            Online acum
          </div>
        </div>
      </div>

      {/* Lead capture form */}
      {!leadSubmitted ? (
        <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "24px", gap: "16px" }}>
          <div style={{ width: "52px", height: "52px", borderRadius: "50%", backgroundColor: primaryColor + "20", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "24px" }}>🤖</div>
          <div style={{ textAlign: "center" }}>
            <p style={{ fontWeight: 700, color: "#0f172a", fontSize: "16px", margin: "0 0 4px" }}>{leadCaptureTitle}</p>
            <p style={{ color: "#64748b", fontSize: "13px", margin: 0 }}>Completeaza datele pentru a incepe conversatia</p>
          </div>
          <form onSubmit={handleLeadSubmit} style={{ width: "100%", maxWidth: "280px", display: "flex", flexDirection: "column", gap: "10px" }}>
            {fields.includes("name") && (
              <input value={leadData.name ?? ""} onChange={(e) => setLeadData(d => ({ ...d, name: e.target.value }))}
                placeholder="Numele tau *" style={{ border: "1px solid #cbd5e1", borderRadius: "10px", padding: "10px 14px", fontSize: "14px", outline: "none" }} />
            )}
            {fields.includes("email") && (
              <input type="email" value={leadData.email ?? ""} onChange={(e) => setLeadData(d => ({ ...d, email: e.target.value }))}
                placeholder="Email *" style={{ border: "1px solid #cbd5e1", borderRadius: "10px", padding: "10px 14px", fontSize: "14px", outline: "none" }} />
            )}
            {fields.includes("phone") && (
              <input type="tel" value={leadData.phone ?? ""} onChange={(e) => setLeadData(d => ({ ...d, phone: e.target.value }))}
                placeholder="Telefon" style={{ border: "1px solid #cbd5e1", borderRadius: "10px", padding: "10px 14px", fontSize: "14px", outline: "none" }} />
            )}
            {leadErrors && <p style={{ color: "#ef4444", fontSize: "12px", margin: 0 }}>{leadErrors}</p>}
            <button type="submit" style={{ backgroundColor: primaryColor, color: "#fff", border: "none", borderRadius: "10px", padding: "11px", fontWeight: 700, fontSize: "14px", cursor: "pointer" }}>
              Incepe conversatia →
            </button>
            <p style={{ fontSize: "11px", color: "#94a3b8", textAlign: "center", margin: 0 }}>Datele tale sunt in siguranta. Nu trimitem spam.</p>
          </form>
        </div>
      ) : (
        <>
          {/* Messages */}
          <div style={{ flex: 1, overflowY: "auto", padding: "16px", display: "flex", flexDirection: "column", gap: "12px" }}>
            {messages.map((msg, i) => {
              const isTyping = msg.role === "assistant" && msg.content === "" && loading && i === messages.length - 1;
              const isLastAssistant = msg.role === "assistant" && i === messages.length - 1 && !loading;
              const cleanContent = msg.content.replace(/\[REZERVARE:\s*\{[\s\S]*?\}\]/gi, "").trim();
              const { text: displayText, buttons } = parseButtons(cleanContent);
              return (
                <div key={i} className="dp-msg" style={{ display: "flex", flexDirection: "column", alignItems: msg.role === "user" ? "flex-end" : "flex-start", gap: "6px" }}>
                  <div style={{ display: "flex", justifyContent: msg.role === "user" ? "flex-end" : "flex-start", alignItems: "flex-end", gap: "8px", width: "100%" }}>
                    {msg.role === "assistant" && (
                      <div style={{ width: "26px", height: "26px", borderRadius: "50%", backgroundColor: primaryColor, display: "flex", alignItems: "center", justifyContent: "center", fontSize: "13px", flexShrink: 0 }}>🤖</div>
                    )}
                    <div style={{
                      maxWidth: "78%", padding: "10px 14px",
                      borderRadius: msg.role === "user" ? "18px 18px 4px 18px" : "18px 18px 18px 4px",
                      backgroundColor: msg.role === "user" ? primaryColor : "#f1f5f9",
                      color: msg.role === "user" ? "#fff" : "#1e293b",
                      lineHeight: "1.55", wordBreak: "break-word",
                    }}>
                      {isTyping ? (
                        <span><span className="dp-dot" /><span className="dp-dot" /><span className="dp-dot" /></span>
                      ) : (
                        <span style={{ whiteSpace: "pre-wrap" }}>{displayText}</span>
                      )}
                    </div>
                  </div>
                  {/* Quick Reply Buttons */}
                  {isLastAssistant && buttons.length > 0 && (
                    <div style={{ display: "flex", flexWrap: "wrap", gap: "6px", paddingLeft: "34px" }}>
                      {buttons.map((btn) => (
                        <button key={btn} onClick={() => sendText(btn)}
                          style={{ border: `1.5px solid ${primaryColor}`, borderRadius: "16px", padding: "6px 14px", fontSize: "13px", fontWeight: 600, color: primaryColor, backgroundColor: "transparent", cursor: "pointer", transition: "all .15s" }}
                          onMouseEnter={e => { (e.target as HTMLElement).style.backgroundColor = primaryColor; (e.target as HTMLElement).style.color = "#fff"; }}
                          onMouseLeave={e => { (e.target as HTMLElement).style.backgroundColor = "transparent"; (e.target as HTMLElement).style.color = primaryColor; }}
                        >{btn}</button>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
            <div ref={bottomRef} />
          </div>

          {/* Branding */}
          {showBranding && (
            <div style={{ textAlign: "center", padding: "4px 0", borderTop: "1px solid #f1f5f9", backgroundColor: "#fff", flexShrink: 0 }}>
              <a href="https://dialpilot.com" target="_blank" rel="noopener noreferrer"
                style={{ fontSize: "10px", color: "#94a3b8", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: "3px", fontWeight: 500, transition: "color .15s" }}
                onMouseEnter={e => { (e.target as HTMLElement).style.color = "#6366f1"; }}
                onMouseLeave={e => { (e.target as HTMLElement).style.color = "#94a3b8"; }}
              >
                ⚡ Powered by <strong style={{ color: "#6366f1" }}>Dialpilot</strong>
              </a>
            </div>
          )}

          {/* Input */}
          <form onSubmit={sendMessage} style={{ display: "flex", gap: "8px", padding: "12px", borderTop: "1px solid #e2e8f0", backgroundColor: "#fff", flexShrink: 0 }}>
            <input ref={inputRef} value={input} onChange={(e) => setInput(e.target.value)} disabled={loading} autoFocus
              placeholder="Scrie un mesaj..."
              style={{ flex: 1, border: "1px solid #cbd5e1", borderRadius: "20px", padding: "10px 16px", fontSize: "14px", outline: "none", backgroundColor: loading ? "#f8fafc" : "#fff" }}
              onFocus={(e) => { e.target.style.borderColor = primaryColor; }}
              onBlur={(e) => { e.target.style.borderColor = "#cbd5e1"; }}
            />
            <button type="submit" disabled={!input.trim() || loading}
              style={{ width: "40px", height: "40px", borderRadius: "50%", border: "none", backgroundColor: !input.trim() || loading ? "#e2e8f0" : primaryColor, color: "#fff", cursor: !input.trim() || loading ? "not-allowed" : "pointer", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "16px", flexShrink: 0 }}>
              ➤
            </button>
          </form>
        </>
      )}
    </div>
  );
}
