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

import { API_BASE } from "./config";
import { Markdown } from "./Markdown";

export function Chatbot({ conversationId, setConversationId, onConversationChanged }) {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [modelList, setModelList] = useState([]);
  const [selectedModel, setSelectedModel] = useState(""); // "" = auto
  const [autoModel, setAutoModel] = useState(null);
  const [showPicker, setShowPicker] = useState(false);
  const [copiedIdx, setCopiedIdx] = useState(null);
  const [lastStats, setLastStats] = useState(null);
  const [memoryToast, setMemoryToast] = useState(null);

  const abortRef = useRef(null);
  const messagesEndRef = useRef(null);
  const pickerRef = useRef(null);

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

  useEffect(() => {
    if (!conversationId) return;
    if (abortRef.current) abortRef.current.abort();
    let cancelled = false;
    setLastStats(null);
    fetch(`${API_BASE}/conversations/${conversationId}`)
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (cancelled) return;
        setMessages(data?.messages?.map(m => ({ role: m.role, content: m.content })) || []);
      })
      .catch(() => { if (!cancelled) setMessages([]); });
    return () => { cancelled = true; };
  }, [conversationId]);

  useEffect(() => {
    Promise.all([
      fetch(`${API_BASE}/models`).then(r => r.ok ? r.json() : null),
      fetch(`${API_BASE}/settings`).then(r => r.ok ? r.json() : null),
    ]).then(([models, settings]) => {
      if (models?.models) setModelList(models.models);
      if (models?.selected) setAutoModel(models.selected);
      if (settings) setSelectedModel(settings.model || "");
    }).catch(() => {});
  }, []);

  useEffect(() => {
    if (!showPicker) return;
    const handle = (e) => {
      if (pickerRef.current && !pickerRef.current.contains(e.target)) setShowPicker(false);
    };
    document.addEventListener("mousedown", handle);
    return () => document.removeEventListener("mousedown", handle);
  }, [showPicker]);

  const setModelChoice = async (model) => {
    setSelectedModel(model);
    setShowPicker(false);
    try {
      await fetch(`${API_BASE}/settings`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ model }),
      });
    } catch { /* persisting the model choice is best-effort */ }
  };

  const startNewChat = () => {
    if (abortRef.current) abortRef.current.abort();
    setInput("");
    setLoading(false);
    setLastStats(null);
    setConversationId(crypto.randomUUID());
  };

  const sendMessage = async () => {
    if (!input.trim() || loading) return;

    const userMessage = input.trim();
    setInput("");

    // Add user message
    setMessages(prev => [...prev, { role: "user", content: userMessage }]);

    // Prepare assistant placeholder
    const assistantIndex = messages.length + 1;
    setMessages(prev => [...prev, { role: "assistant", content: "" }]);

    setLoading(true);

    // Abort previous stream if still open
    if (abortRef.current) abortRef.current.abort();
    const controller = new AbortController();
    abortRef.current = controller;

    try {
      // Exclude the empty assistant placeholder that was just appended
      const historySnapshot = messages.filter(m => m.content.trim() !== "");

      const response = await fetch(`${API_BASE}/chat/stream`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          message: userMessage,
          conversation_id: conversationId,
          history: historySnapshot.map(m => ({ role: m.role, content: m.content })),
        }),
        signal: controller.signal,
      });

      if (!response.ok) {
        const text = await response.text();
        updateAssistant(assistantIndex, `Error: ${text}`);
        setLoading(false);
        return;
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      let buffer = "";
      let pendingEventType = null;

      while (true) {
        const { value, done } = 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("event: ")) {
            pendingEventType = line.slice(7).trim();
            continue;
          }
          if (line.startsWith("data: ")) {
            const payload = line.slice(6);
            if (!payload.trim()) { pendingEventType = null; continue; }

            if (pendingEventType === "meta") {
              try {
                const stats = JSON.parse(payload);
                setLastStats(stats);
                // Tag this message with the model that answered
                if (stats.model) {
                  setMessages(prev => {
                    const updated = [...prev];
                    updated[assistantIndex] = { ...updated[assistantIndex], model: stats.model };
                    return updated;
                  });
                }
              } catch { /* ignore */ }
              pendingEventType = null;
              continue;
            }
            if (pendingEventType === "memory") {
              try {
                const mem = JSON.parse(payload);
                setMemoryToast(mem);
                setTimeout(() => setMemoryToast(null), 5000);
              } catch { /* ignore */ }
              pendingEventType = null;
              continue;
            }
            if (pendingEventType === "done") {
              // Answer is complete; re-enable input while the backend finishes
              // slow post-processing (title, memory) on the still-open stream.
              setLoading(false);
              pendingEventType = null;
              continue;
            }
            if (pendingEventType === "title") {
              if (onConversationChanged) onConversationChanged();
              pendingEventType = null;
              continue;
            }
            if (pendingEventType === "error") {
              try {
                const err = JSON.parse(payload);
                updateAssistant(assistantIndex, `Error: ${err.detail || payload}`);
              } catch {
                updateAssistant(assistantIndex, `Error: ${payload}`);
              }
              pendingEventType = null;
              setLoading(false);
              return;
            }
            pendingEventType = null;

            let token = payload;
            try { token = JSON.parse(payload); } catch { /* plain text fallback */ }

            setMessages(prev => {
              const updated = [...prev];
              updated[assistantIndex] = {
                ...updated[assistantIndex],
                content: (updated[assistantIndex].content || "") + token,
              };
              return updated;
            });
          }
        }
      }
      
    } catch (err) {
      if (err.name !== "AbortError") {
        updateAssistant(assistantIndex, `Connection error: ${err.message}`);
      }
    } finally {
      setLoading(false);
      if (onConversationChanged) onConversationChanged();
    }
  };

  const updateAssistant = (index, text) => {
    setMessages(prev => {
      const updated = [...prev];
      updated[index] = { ...updated[index], content: text };
      return updated;
    });
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%", flexGrow: 1 }}>
      {memoryToast && (
        <div style={{
          position: "fixed", bottom: "1.5rem", right: "1.5rem",
          background: "#1a1a2e", border: "1px solid #7c3aed",
          borderRadius: "8px", padding: "0.6rem 1rem",
          fontSize: "0.85rem", color: "#c4b5fd",
          boxShadow: "0 4px 12px rgba(0,0,0,0.5)", zIndex: 9999,
          maxWidth: "320px"
        }}>
          🧠 <strong>Memory saved</strong> [{memoryToast.section}]<br />
          <span style={{ color: "#aaa", fontSize: "0.8rem" }}>{memoryToast.text}</span>
        </div>
      )}
      <div style={{
        flexGrow: 1,
        background: "#161616",
        border: "1px solid #333",
        borderRadius: "12px",
        padding: "1rem",
        display: "flex",
        flexDirection: "column",
        overflow: "hidden"
      }}>
        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "0.75rem" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "0.75rem" }}>
            <span style={{ fontSize: "0.85rem", color: "#555" }}>
              {messages.length === 0 ? "New conversation" : `${Math.ceil(messages.length / 2)} exchange${messages.length > 2 ? "s" : ""}`}
            </span>
            <div ref={pickerRef} style={{ position: "relative" }}>
              <button
                onClick={() => setShowPicker(p => !p)}
                style={{
                  fontSize: "0.7rem",
                  color: "#7aa",
                  background: showPicker ? "#1e2e2e" : "#1a2a2a",
                  border: "1px solid #2a4a4a",
                  borderRadius: "4px",
                  padding: "0.15rem 0.5rem",
                  cursor: "pointer",
                  letterSpacing: "0.03em",
                  display: "flex",
                  alignItems: "center",
                  gap: "0.3rem",
                }}
              >
                {!selectedModel && <span style={{ color: "#4a6a6a" }}>auto ·</span>}
                {selectedModel || autoModel || "no model"}
                <span style={{ color: "#4a7a7a", fontSize: "0.6rem" }}>▾</span>
              </button>
              {showPicker && (
                <div style={{
                  position: "absolute",
                  top: "calc(100% + 4px)",
                  left: 0,
                  background: "#1a1a1a",
                  border: "1px solid #333",
                  borderRadius: "8px",
                  zIndex: 100,
                  minWidth: "200px",
                  maxHeight: "240px",
                  overflowY: "auto",
                  boxShadow: "0 4px 16px rgba(0,0,0,0.6)",
                }}>
                  <div
                    onClick={() => setModelChoice("")}
                    style={{
                      padding: "0.55rem 0.85rem",
                      cursor: "pointer",
                      fontSize: "0.8rem",
                      color: !selectedModel ? "#7aa" : "#888",
                      background: !selectedModel ? "#1a2a2a" : "transparent",
                      borderBottom: "1px solid #262626",
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                    }}
                  >
                    <span>Auto <span style={{ color: "#445", fontSize: "0.7rem" }}>{autoModel ? `(${autoModel})` : ""}</span></span>
                    {!selectedModel && <span>✓</span>}
                  </div>
                  {modelList.map(m => (
                    <div
                      key={m}
                      onClick={() => setModelChoice(m)}
                      style={{
                        padding: "0.55rem 0.85rem",
                        cursor: "pointer",
                        fontSize: "0.8rem",
                        color: selectedModel === m ? "#7aa" : "#ccc",
                        background: selectedModel === m ? "#1a2a2a" : "transparent",
                        display: "flex",
                        justifyContent: "space-between",
                        alignItems: "center",
                      }}
                    >
                      <span>{m}</span>
                      {selectedModel === m && <span>✓</span>}
                    </div>
                  ))}
                </div>
              )}
            </div>
            {lastStats && (
              <span style={{
                fontSize: "0.7rem",
                color: "#888",
                background: "#1a1a1a",
                border: "1px solid #2a2a2a",
                borderRadius: "4px",
                padding: "0.15rem 0.45rem",
              }}>
                {lastStats.tokens} tok · {lastStats.elapsed_s}s
                {lastStats.tokens_per_s > 0 ? ` · ${lastStats.tokens_per_s} t/s` : ""}
              </span>
            )}
          </div>
          <button
            onClick={startNewChat}
            disabled={loading}
            style={{
              padding: "0.4rem 0.85rem",
              background: "#222",
              color: "#aaa",
              border: "1px solid #444",
              borderRadius: "6px",
              cursor: loading ? "default" : "pointer",
              fontSize: "0.8rem",
              opacity: loading ? 0.5 : 1,
            }}
          >
            New Chat
          </button>
        </div>

        <div style={{
          flexGrow: 1,
          overflowY: "auto",
          marginBottom: "1rem",
          paddingRight: "0.5rem"
        }}>
          {messages.length === 0 ? (
            <div style={{ color: "#666", textAlign: "center", paddingTop: "2rem" }}>
              <p>Start a conversation with the chatbot...</p>
            </div>
          ) : (
            messages.map((msg, idx) => (
              <div
                key={idx}
                style={{
                  marginBottom: "1rem",
                  display: "flex",
                  flexDirection: "column",
                  alignItems: msg.role === "user" ? "flex-end" : "flex-start",
                }}
              >
                <div
                  style={{
                    maxWidth: msg.role === "user" ? "70%" : "90%",
                    width: msg.role === "assistant" ? "100%" : undefined,
                    padding: "0.9rem",
                    borderRadius: "10px",
                    background: msg.role === "user" ? "#007acc" : "#262626",
                    color: "#eee",
                    wordWrap: "break-word",
                    boxSizing: "border-box",
                  }}
                >
                  {msg.role === "user"
                    ? <span style={{ whiteSpace: "pre-wrap" }}>{msg.content}</span>
                      : msg.content
                      ? <Markdown content={msg.content} />
                      : <span style={{ color: "#aaa" }}>Thinking...</span>
                  }
                </div>
                {msg.content && (
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(msg.content).then(() => {
                        setCopiedIdx(idx);
                        setTimeout(() => setCopiedIdx(null), 1500);
                      });
                    }}
                    style={{
                      marginTop: "0.25rem",
                      padding: "0.15rem 0.5rem",
                      fontSize: "0.7rem",
                      color: copiedIdx === idx ? "#4caf50" : "#555",
                      background: "transparent",
                      border: "none",
                      cursor: "pointer",
                    }}
                  >
                    {copiedIdx === idx ? "Copied!" : "Copy"}
                  </button>
                )}
              </div>
            ))
          )}

<div ref={messagesEndRef} />
        </div>

        <div style={{ display: "flex", gap: "0.75rem", alignItems: "flex-end" }}>
          <textarea
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Type your message... (Shift+Enter for new line)"
            disabled={loading}
            rows={3}
            style={{
              flexGrow: 1,
              padding: "0.9rem",
              background: "#222",
              color: "#eee",
              border: "1px solid #333",
              borderRadius: "10px",
              fontFamily: "system-ui",
              resize: "none",
              opacity: loading ? 0.6 : 1
            }}
          />
          <button
            onClick={sendMessage}
            disabled={loading || !input.trim()}
            style={{
              padding: "0.9rem 1.5rem",
              background: loading || !input.trim() ? "#555" : "#007acc",
              color: "#fff",
              border: "none",
              borderRadius: "8px",
              cursor: loading || !input.trim() ? "default" : "pointer",
              opacity: loading || !input.trim() ? 0.6 : 1,
            }}
          >
            Send
          </button>
        </div>
      </div>
    </div>
  );
}