import React from "react";

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

export default function AIAssistantDrawer({ open, onClose, computers, scope, setScope }) {
  const [messages, setMessages] = useState([
    { role: "assistant", text: "Постави прашање за Sysmon, процеси, мрежа. Можеш да избереш компјутер (scope) горе." },
  ]);
  const [input, setInput] = useState("");
  const [sending, setSending] = useState(false);
  const bottomRef = useRef(null);

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

  async function send() {
    const q = input.trim();
    if (!q || sending) return;

    setInput("");
    setMessages((m) => [...m, { role: "user", text: q }]);
    setSending(true);

    try {
      const r = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question: q, computer_name: scope || null }),
      });
      const data = await r.json();
      setMessages((m) => [...m, { role: "assistant", text: data.answer || "(no answer)" }]);
    } catch (e) {
      setMessages((m) => [...m, { role: "assistant", text: `Грешка: ${String(e.message || e)}` }]);
    } finally {
      setSending(false);
    }
  }

  if (!open) return null;

  return (
    <>
      <div className="drawer-backdrop" onMouseDown={onClose} />
      <div className="drawer" onMouseDown={(e) => e.stopPropagation()}>
        <div className="drawer-head">
          <div>
            <div className="drawer-title">🤖 AI Assistant</div>
            <div className="drawer-sub">Uses /api/chat (RAG over your logs)</div>
          </div>
          <button className="btn" onClick={onClose}>Close</button>
        </div>

        <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border)" }}>
          <div className="row">
            <select className="select" value={scope || ""} onChange={(e) => setScope(e.target.value || null)}>
              <option value="">All computers</option>
              {(computers || []).map((c) => (
                <option key={c.name} value={c.name}>{c.name}</option>
              ))}
            </select>
          </div>
          <div className="small">Tip: “Top процеси по RAM” или “сомнителни sysmon events”</div>
        </div>

        <div className="drawer-body">
          {messages.map((m, i) => (
            <div key={i} className={`bubble ${m.role === "user" ? "user" : ""}`}>
              <div style={{ fontSize: 11, color: "var(--dim)", marginBottom: 6 }}>
                {m.role === "user" ? "You" : "Assistant"}
              </div>
              <div style={{ whiteSpace: "pre-wrap" }}>{m.text}</div>
            </div>
          ))}
          <div ref={bottomRef} />
        </div>

        <div className="drawer-foot">
          <div className="row">
            <textarea
              className="textarea"
              rows={2}
              value={input}
              placeholder="Постави прашање… (Enter = send, Shift+Enter нов ред)"
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  send();
                }
              }}
            />
            <button className="btn primary" onClick={send} disabled={sending || !input.trim()}>
              {sending ? "Sending…" : "Send"}
            </button>
          </div>
        </div>
      </div>
    </>
  );
}
