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

function renderInline(text, keyPrefix) {
  const parts = String(text || "").split(/(\*\*[^*]+\*\*)/g);
  return parts.map((part, idx) => {
    if (part.startsWith("**") && part.endsWith("**") && part.length > 4) {
      return <strong key={`${keyPrefix}-b-${idx}`}>{part.slice(2, -2)}</strong>;
    }
    return <span key={`${keyPrefix}-t-${idx}`}>{part}</span>;
  });
}

function renderSimpleMarkdown(text) {
  const lines = String(text || "").split("\n");
  const blocks = [];
  let listItems = [];

  const flushList = (key) => {
    if (!listItems.length) return;
    blocks.push(
      <ul key={`ul-${key}`}>
        {listItems.map((item, idx) => (
          <li key={`li-${key}-${idx}`}>{renderInline(item, `li-${key}-${idx}`)}</li>
        ))}
      </ul>
    );
    listItems = [];
  };

  lines.forEach((rawLine, index) => {
    const line = rawLine.trimEnd();
    const trimmed = line.trim();

    if (!trimmed) {
      flushList(index);
      return;
    }

    if (trimmed.startsWith("- ")) {
      listItems.push(trimmed.slice(2));
      return;
    }

    flushList(index);

    if (trimmed.startsWith("## ")) {
      blocks.push(<h2 key={`h2-${index}`}>{renderInline(trimmed.slice(3), `h2-${index}`)}</h2>);
      return;
    }

    if (trimmed.startsWith("# ")) {
      blocks.push(<h1 key={`h1-${index}`}>{renderInline(trimmed.slice(2), `h1-${index}`)}</h1>);
      return;
    }

    blocks.push(<p key={`p-${index}`}>{renderInline(trimmed, `p-${index}`)}</p>);
  });

  flushList("end");
  return blocks;
}

export default function AiChatbotPage() {
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);
  const [warmingUp, setWarmingUp] = useState(true);
  const timelineRef = useRef(null);
  const sessionIdRef = useRef("");
  const streamBufferRef = useRef("");
  const flushTimerRef = useRef(null);
  const streamDoneRef = useRef(false);
  const STREAM_FLUSH_MS = 48;
  const [chat, setChat] = useState([
    {
      role: "assistant",
      text: "Xin chào, mình là BridgeUp Assistant. Bạn muốn tìm hiểu gì về hệ sinh thái BridgeUp?",
    },
  ]);

  if (!sessionIdRef.current) {
    const key = "bridgeup_session_id";
    const existing = window.localStorage.getItem(key);
    if (existing) {
      sessionIdRef.current = existing;
    } else {
      const created = `sess_${Math.random().toString(36).slice(2)}_${Date.now()}`;
      window.localStorage.setItem(key, created);
      sessionIdRef.current = created;
    }
  }

  function scrollToBottom() {
    if (!timelineRef.current) return;
    timelineRef.current.scrollTop = timelineRef.current.scrollHeight;
  }

  function clearFlushTimer() {
    if (flushTimerRef.current) {
      window.clearInterval(flushTimerRef.current);
      flushTimerRef.current = null;
    }
  }

  function startBufferedFlush(assistantIndex) {
    clearFlushTimer();
    flushTimerRef.current = window.setInterval(() => {
      if (!streamBufferRef.current && !streamDoneRef.current) return;

      const nextText = streamBufferRef.current;
      streamBufferRef.current = "";

      setChat((prev) => {
        const next = [...prev];
        if (next[assistantIndex] && nextText) {
          next[assistantIndex] = {
            ...next[assistantIndex],
            text: (next[assistantIndex].text || "") + nextText,
          };
        }
        return next;
      });

      requestAnimationFrame(scrollToBottom);

      if (streamDoneRef.current && !streamBufferRef.current) {
        clearFlushTimer();
      }
    }, STREAM_FLUSH_MS);
  }

  function flushRemainingBuffer(assistantIndex) {
    if (!streamBufferRef.current) return;
    const pending = streamBufferRef.current;
    streamBufferRef.current = "";

    setChat((prev) => {
      const next = [...prev];
      if (next[assistantIndex]) {
        next[assistantIndex] = {
          ...next[assistantIndex],
          text: (next[assistantIndex].text || "") + pending,
        };
      }
      return next;
    });
    requestAnimationFrame(scrollToBottom);
  }

  async function sendMessage() {
    const content = message.trim();
    if (!content || loading) return;

    setMessage("");
    setLoading(true);

    const assistantIndex = chat.length + 1;
    setChat((prev) => [...prev, { role: "user", text: content }, { role: "assistant", text: "" }]);

    try {
      const response = await fetch("/api/chat/stream", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          message: content,
          sessionId: sessionIdRef.current,
          history: chat.map((item) => ({ role: item.role, content: item.text })),
        }),
      });

      if (!response.ok || !response.body) {
        const data = await response.json().catch(() => ({}));
        throw new Error(data?.error || "Request failed");
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let fullText = "";
      streamBufferRef.current = "";
      streamDoneRef.current = false;
      startBufferedFlush(assistantIndex);

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        fullText += chunk;
        streamBufferRef.current += chunk;
      }
      streamDoneRef.current = true;
      flushRemainingBuffer(assistantIndex);

      if (!fullText.trim()) {
        const retryResp = await fetch("/api/chat", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            message: content,
            sessionId: sessionIdRef.current,
            history: chat.map((item) => ({ role: item.role, content: item.text })),
          }),
        });

        const retryData = await retryResp.json().catch(() => ({}));
        const retryAnswer = retryData?.answer || "Không có phản hồi.";

        setChat((prev) => {
          const next = [...prev];
          if (next[assistantIndex]) {
            next[assistantIndex] = { role: "assistant", text: retryAnswer };
          }
          return next;
        });
      }
    } catch (error) {
      flushRemainingBuffer(assistantIndex);
      clearFlushTimer();
      setChat((prev) => {
        const next = [...prev];
        if (next[assistantIndex]) {
          next[assistantIndex] = {
            role: "assistant",
            text: `Có lỗi xảy ra: ${error.message}`,
          };
        }
        return next;
      });
    } finally {
      flushRemainingBuffer(assistantIndex);
      clearFlushTimer();
      setLoading(false);
    }
  }

  function onEnterSubmit(event) {
    if (event.key === "Enter" && !event.shiftKey) {
      event.preventDefault();
      sendMessage();
    }
  }

  useEffect(() => {
    requestAnimationFrame(scrollToBottom);
  }, [chat, loading]);

  useEffect(() => {
    let cancelled = false;

    async function warmup() {
      try {
        await fetch("/api/chat/warmup");
      } catch {
        // ignore warmup failures
      } finally {
        if (!cancelled) setWarmingUp(false);
      }
    }

    warmup();
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => () => clearFlushTimer(), []);

  return (
    <section className="section page-banner ai-chatbot-exact">
      <div className="ai-shell">
        <section className="ai-chat-frame">
          <header className="ai-topbar">
            <div className="ai-brand">
              <p className="ai-brand-kicker">Project Demo</p>
              <h1>BridgeUp Insight Studio</h1>
              <p className="ai-brand-subtitle">AI conversation workspace for GrowCap, LearnCap, and ChallengeCap.</p>
            </div>
          </header>

          <main className="ai-timeline" ref={timelineRef}>
            {chat.map((item, idx) => (
              <article key={`${item.role}-${idx}`} className={`ai-msg-row ${item.role}`}>
                {item.role === "assistant" ? (
                  <div className="ai-coach-label">
                    <span className="ai-coach-dot">✥</span>
                    <span>BridgeUp Coach</span>
                  </div>
                ) : null}

                <div className={`ai-bubble ${item.role}`}>
                  {item.role === "assistant" ? renderSimpleMarkdown(item.text || "Đang suy nghĩ...") : <p>{item.text}</p>}
                </div>
              </article>
            ))}
          </main>

          {loading || warmingUp ? (
            <div className="ai-typing-status">{loading ? "Đang phân tích..." : "Đang khởi động AI..."}</div>
          ) : null}

          <footer className="ai-composer-wrap">
            <button className="ai-clip-btn" type="button" aria-label="Attach">
              ⎋
            </button>

            <div className="ai-composer">
              <textarea
                value={message}
                onChange={(event) => setMessage(event.target.value)}
                onKeyDown={onEnterSubmit}
                placeholder="Ask about your communication patterns..."
              />
            </div>

            <button className="ai-send-btn" onClick={sendMessage} disabled={loading}>
              ➤
            </button>
          </footer>
        </section>
      </div>
    </section>
  );
}
