import React, {useEffect, useMemo, useState} from "react";
import "./styles/theme.css";

import Login from "./components/Login";
import TopBar from "./components/TopBar";
import ComputerCard from "./components/ComputerCard";
import ComputerDetailsModal from "./components/ComputerDetailsModal";
import AIAssistantDrawer from "./components/AIAssistantDrawer";

export default function App() {
    const [stats, setStats] = useState(null);
    const [computers, setComputers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [lastUpdated, setLastUpdated] = useState(null);

    const [query, setQuery] = useState("");
    const [status, setStatus] = useState("");

    const [selectedComputer, setSelectedComputer] = useState(null);
    const [aiOpen, setAiOpen] = useState(false);
    const [aiScope, setAiScope] = useState(null);
    const [selectedEnv, setSelectedEnv] = useState("default");

    const [me, setMe] = useState(null);
    const [meLoading, setMeLoading] = useState(true);

    // const [openAI, setOpenAI] = useState(false);
    // const [scope, setScope] = useState(null);


    async function loadMe() {
        setMeLoading(true);
        try {
            const r = await fetch("/api/me", {credentials: "include"});
            if (r.ok) {
                const data = await r.json();
                setMe(data.user);
            } else {
                setMe(null);
            }
        } catch (e) {
            console.error("loadMe error", e);
            setMe(null);
        } finally {
            setMeLoading(false);
        }
    }

    async function refresh() {
        try {
            setLoading(true);
            const [s, c] = await Promise.all([
                fetch("/api/stats", {credentials: "include"}).then((r) => r.json()),
                fetch("/api/computers", {
                    credentials: "include",
                    headers: {"X-Env": selectedEnv},
                }).then((r) => r.json()),
            ]);

            setStats(s);
            setComputers(Array.isArray(c) ? c : []);
            setLastUpdated(new Date().toISOString());
        } catch (e) {
            console.error("refresh error", e);
        } finally {
            setLoading(false);
        }
    }

    // on mount: check session
    useEffect(() => {
        loadMe();
    }, []);

    // when logged in OR env changed, refresh data
    useEffect(() => {
        if (me) refresh();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [me, selectedEnv]);

    const filtered = useMemo(() => {
        const q = query.trim().toLowerCase();
        return (computers || [])
            .filter((c) => (status ? c.status === status : true))
            .filter((c) => {
                if (!q) return true;
                const hay = [c.name, c.user, c.ip, c.os, c.status]
                    .filter(Boolean)
                    .join(" ")
                    .toLowerCase();
                return hay.includes(q);
            });
    }, [computers, query, status]);

    // Gate UI
    if (meLoading) return <div style={{padding: 20}}>Loading…</div>;
    if (!me) return <Login onDone={loadMe}/>;

    return (
        <div className="app-wrap">
            <TopBar
                onOpenAI={() => setAiOpen(true)}
                onRefresh={refresh}
                lastUpdated={lastUpdated}
                onEnvChange={(env) => setSelectedEnv(env)}
                selectedEnv={selectedEnv}
                me={me}
                onLoggedOut={loadMe}
            />


            {/* STATS */}
            <div className="stats-grid">
                <div className="stat-card">
                    <div className="label">Total Computers</div>
                    <div className="value">{computers.length}</div>
                    <div className="sub">Monitored Systems</div>
                </div>

                <div className="stat-card">
                    <div className="label">Sysmon Events (24h)</div>
                    <div className="value">{stats?.total_sysmon_events ?? "—"}</div>
                    <div className="sub">Security Events</div>
                </div>

                <div className="stat-card">
                    <div className="label">Network Connections (24h)</div>
                    <div className="value">{stats?.total_network_connections ?? "—"}</div>
                    <div className="sub">Captured Connections</div>
                </div>
            </div>

            {/* FILTERS */}
            <div className="panel" style={{marginBottom: 14}}>
                <div className="panel-head">
                    <div className="panel-title">Filters</div>
                    <div style={{color: "var(--dim)", fontSize: 12}}>
                        {loading ? "Refreshing…" : `${filtered.length} shown`}
                    </div>
                </div>
                <div className="panel-body">
                    <div className="filters">
                        <input
                            className="input"
                            value={query}
                            onChange={(e) => setQuery(e.target.value)}
                            placeholder="Search by name / user / ip / os…"
                        />

                        <select
                            className="select"
                            value={status}
                            onChange={(e) => setStatus(e.target.value)}
                        >
                            <option value="">All status</option>
                            <option value="online">Online</option>
                            <option value="idle">Idle</option>
                            <option value="offline">Offline</option>
                        </select>

                        <button className="btn primary" onClick={refresh}>
                            Refresh
                        </button>
                    </div>
                </div>
            </div>

            {/* COMPUTERS */}
            <div className="panel">
                <div className="panel-head">
                    <div className="panel-title">Connected Computers</div>
                    <div style={{display: "flex", gap: 10, alignItems: "center"}}>
                        <span className="pill">{filtered.length} computers</span>
                        <button
                            className="btn"
                            onClick={() => {
                                setQuery("");
                                setStatus("");
                            }}
                        >
                            Reset
                        </button>
                    </div>
                </div>
                <div className="panel-body">
                    <div className="computers-grid">
                        {filtered.map((c) => (
                            <ComputerCard
                                key={c.name}
                                c={c}
                                onOpen={(pc) => {
                                    setSelectedComputer(pc);
                                    setAiScope(pc.name);
                                }}
                            />
                        ))}
                        {filtered.length === 0 && (
                            <div style={{color: "var(--dim)"}}>
                                No computers match filter.
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* DETAILS MODAL */}
            <ComputerDetailsModal
                open={!!selectedComputer}
                computer={selectedComputer}
                onClose={() => setSelectedComputer(null)}
                onAskAI={(name) => {
                    setAiScope(name);
                    setAiOpen(true);
                }}
            />

            {/* AI DRAWER */}
            {/*<button onClick={() => setOpenAI(true)}>AI</button>*/}

            {/*<AIAssistantDrawer*/}
            {/*    open={openAI}*/}
            {/*    onClose={() => setOpenAI(false)}*/}
            {/*    computers={computers}*/}
            {/*    scope={scope}*/}
            {/*    setScope={setScope}*/}
            {/*    apiBase={import.meta.env.VITE_API_BASE}*/}
            {/*/>*/}

            <AIAssistantDrawer
                open={aiOpen}
                onClose={() => setAiOpen(false)}
                computers={computers}
                scope={aiScope}
                setScope={setAiScope}
                apiBase={import.meta.env.VITE_API_BASE}
            />


        </div>
    );
}
