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

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

    useEffect(() => {
        if (open) {
            // затвори со Escape
            const onKey = (e) => {
                if (e.key === "Escape") onClose?.();
            };
            window.addEventListener("keydown", onKey);
            return () => window.removeEventListener("keydown", onKey);
        }
    }, [open, onClose]);

    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 base = (apiBase || "").replace(/\/$/, ""); // тргни trailing /
            const url = `${base}/api/chat`;

            const r = await fetch(url, {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                credentials: "include",
                body: JSON.stringify({question: q, computer_name: scope || null}),
            });


            const data = await r.json().catch(() => ({}));
            if (!r.ok) {
                setMessages((m) => [...m, {
                    role: "assistant",
                    text: `Error ${r.status}: ${data.error || "Request failed"}`
                }]);
            } else {
                setMessages((m) => [...m, {role: "assistant", text: data.answer || "(no answer)"}]);
            }
            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="aiDrawer-backdrop" onMouseDown={onClose}/>

            <aside
                className="aiDrawer"
                role="dialog"
                aria-modal="true"
                onMouseDown={(e) => e.stopPropagation()}
            >
                <header className="aiDrawer-head">
                    <div>
                        <div className="aiDrawer-title">🤖 AI Assistant</div>
                        <div className="aiDrawer-sub">RAG over your logs</div>
                    </div>

                    <button className="aiBtn" onClick={onClose} aria-label="Close">
                        ✕
                    </button>
                </header>

                <div className="aiDrawer-toolbar">
                    <select
                        className="aiSelect"
                        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 className="aiHint">
                        Tip: “Top процеси по RAM” / “сомнителни sysmon events”
                    </div>
                </div>

                <main className="aiDrawer-body">
                    {messages.map((m, i) => (
                        <div
                            key={i}
                            className={`aiMsg ${m.role === "user" ? "user" : "assistant"}`}
                        >
                            <div className="aiMsg-meta">{m.role === "user" ? "You" : "Assistant"}</div>
                            <div className="aiMsg-text">{m.text}</div>
                        </div>
                    ))}
                    <div ref={bottomRef}/>
                </main>

                <footer className="aiDrawer-foot">
          <textarea
              className="aiTextarea"
              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="aiBtn aiBtnPrimary"
                        onClick={send}
                        disabled={sending || !input.trim()}
                    >
                        {sending ? "Sending…" : "Send"}
                    </button>
                </footer>
            </aside>
        </>
    );
}
