import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Bot, ExternalLink, RefreshCw } from "lucide-react";
import { Button } from "../../components/ui/button";
import { cn } from "../../lib/utils";
import { getActiveAgents } from "../../editor/services/agentService";
import { isTerminalAgentStatus, parseAgentRunStatusData, } from "../../editor/services/agentStatus";
import { useEditContext } from "../../editor/client/editContext";
function getAgentContextString(agent) {
    const anyAgent = agent;
    const ctx = anyAgent?.agentContext ?? null;
    return typeof ctx === "string" ? ctx : null;
}
function agentMatchesProject(agent, projectId) {
    const ctxStr = getAgentContextString(agent);
    if (!ctxStr)
        return false;
    // Fast path: substring match on canonical JSON payload
    if (ctxStr.includes(`"projectId":"${projectId}"`))
        return true;
    // Safe path: parse and check additionalData
    try {
        const parsed = JSON.parse(ctxStr);
        const fromAdditional = parsed?.additionalData?.projectId;
        if (typeof fromAdditional === "string" && fromAdditional === projectId)
            return true;
        if (typeof parsed?.projectId === "string" && parsed.projectId === projectId)
            return true;
    }
    catch {
        // ignore non-JSON contexts
    }
    return false;
}
function formatAgentStatus(status) {
    return status;
}
function sortAgentsByUpdatedDate(agents) {
    return [...agents].sort((a, b) => {
        return (b.updatedDate ?? "").localeCompare(a.updatedDate ?? "");
    });
}
export function ProjectAgentsPanel(props) {
    const { project } = props;
    const editContext = useEditContext();
    const [agents, setAgents] = useState([]);
    const [loading, setLoading] = useState(false);
    const projectId = project?.project.projectId ?? null;
    const refresh = useCallback(async () => {
        if (!projectId) {
            setAgents([]);
            return;
        }
        setLoading(true);
        try {
            const response = await getActiveAgents({
                limit: 1000,
                includeOwned: true,
                includeShared: true,
                excludeClosed: true,
            });
            const filtered = (response.agents ?? []).filter((a) => agentMatchesProject(a, projectId));
            setAgents(sortAgentsByUpdatedDate(filtered));
        }
        finally {
            setLoading(false);
        }
    }, [projectId]);
    useEffect(() => {
        refresh();
        // Also refetch on socket reconnect
    }, [refresh, editContext?.socketConnectionVersion]);
    useEffect(() => {
        if (!editContext?.addSocketMessageListener)
            return;
        const unsubscribe = editContext.addSocketMessageListener((message) => {
            const t = message?.type;
            if (t === "agent:run:start") {
                // A new agent may belong to this project, so reload once.
                void refresh();
                return;
            }
            if (t === "agent:run:status") {
                const agentId = message?.payload?.agentId;
                const nextStatus = parseAgentRunStatusData(message?.payload?.data);
                if (!agentId || !nextStatus)
                    return;
                setAgents((prevAgents) => {
                    const existingIndex = prevAgents.findIndex((agent) => agent.id === agentId);
                    if (existingIndex === -1)
                        return prevAgents;
                    if (isTerminalAgentStatus(nextStatus)) {
                        return prevAgents.filter((agent) => agent.id !== agentId);
                    }
                    const updatedAgents = [...prevAgents];
                    updatedAgents[existingIndex] = {
                        ...updatedAgents[existingIndex],
                        status: nextStatus,
                        updatedDate: new Date().toISOString(),
                    };
                    return sortAgentsByUpdatedDate(updatedAgents);
                });
                return;
            }
            if (t === "agent:run:complete" || t === "agent:run:error" || t === "agent:run:closed") {
                const agentId = message?.payload?.agentId;
                if (!agentId)
                    return;
                setAgents((prevAgents) => prevAgents.filter((agent) => agent.id !== agentId));
                return;
            }
            if (t === "agent:info:updated") {
                const agentId = message?.payload?.agentId;
                if (!agentId)
                    return;
                setAgents((prevAgents) => {
                    const existingIndex = prevAgents.findIndex((agent) => agent.id === agentId);
                    if (existingIndex === -1)
                        return prevAgents;
                    const updatedAgents = [...prevAgents];
                    updatedAgents[existingIndex] = {
                        ...updatedAgents[existingIndex],
                        ...(message?.payload?.agentName !== undefined && {
                            name: message.payload.agentName,
                        }),
                        ...(message?.payload?.agentDescription !== undefined && {
                            description: message.payload.agentDescription,
                        }),
                        updatedDate: new Date().toISOString(),
                    };
                    return sortAgentsByUpdatedDate(updatedAgents);
                });
            }
        });
        return () => unsubscribe();
    }, [editContext?.addSocketMessageListener, refresh]);
    const openAgent = useCallback((agentId) => {
        editContext?.setShowAgentsPanel?.(true);
        window.dispatchEvent(new CustomEvent("editor:openAgent", { detail: { agentId } }));
    }, [editContext]);
    const canSee = Boolean(projectId);
    const countLabel = useMemo(() => {
        if (!canSee)
            return "Select a project";
        if (loading)
            return "Loading…";
        return agents.length === 1 ? "1 agent" : `${agents.length} agents`;
    }, [agents.length, canSee, loading]);
    if (!project)
        return null;
    return (_jsxs("div", { className: "flex h-full flex-col border-l bg-white", children: [_jsxs("div", { className: "flex items-center justify-between border-b px-4 py-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Bot, { className: "h-5 w-5 text-muted-foreground" }), _jsxs("div", { children: [_jsx("div", { className: "text-sm font-semibold", children: "Project agents" }), _jsx("div", { className: "text-xs text-muted-foreground", children: countLabel })] })] }), _jsx(Button, { variant: "ghost", size: "sm", onClick: refresh, disabled: loading || !projectId, children: _jsx(RefreshCw, { className: cn("h-4 w-4", loading && "animate-spin") }) })] }), _jsx("div", { className: "flex-1 overflow-auto p-3", children: !projectId ? (_jsx("div", { className: "p-3 text-xs text-muted-foreground", children: "Select a project to see its agents." })) : agents.length === 0 ? (_jsx("div", { className: "p-3 text-xs text-muted-foreground", children: "No active agents found for this project yet." })) : (_jsx("div", { className: "space-y-2", children: agents.map((a) => {
                        const status = formatAgentStatus(a.status);
                        return (_jsxs("button", { onClick: () => openAgent(a.id), className: "w-full rounded-md border bg-white p-3 text-left hover:bg-muted/30", children: [_jsxs("div", { className: "flex items-start justify-between gap-2", children: [_jsxs("div", { className: "min-w-0", children: [_jsx("div", { className: "truncate text-sm font-medium", children: a.name || a.profileName || a.id }), _jsxs("div", { className: "mt-0.5 flex flex-wrap items-center gap-2 text-xs text-muted-foreground", children: [a.profileName && _jsx("span", { children: a.profileName }), _jsx("span", { className: "rounded bg-muted px-1.5 py-0.5", children: status })] })] }), _jsx(ExternalLink, { className: "h-4 w-4 shrink-0 text-muted-foreground" })] }), a.description ? (_jsx("div", { className: "mt-2 line-clamp-2 text-xs text-muted-foreground", children: a.description })) : null] }, a.id));
                    }) })) })] }));
}
//# sourceMappingURL=ProjectAgentsPanel.js.map