import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AlertCircle, CheckCircle, Plus, RefreshCw, Search, Settings, Shield, } from "lucide-react";
import { useSearchParams } from "../../client/navigation";
import { Button } from "../../../components/ui/button";
import { Input } from "../../../components/ui/input";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { useEditContext } from "../../client/editContext";
import { Splitter } from "../../ui/Splitter";
import { SecretAgentIcon } from "../../ui/Icons";
import { AgentProfileEditorPanel } from "./AgentProfileEditorPanel";
import { CreateAgentProfileDialog } from "./CreateAgentProfileDialog";
const SELECTED_AGENT_QUERY_PARAM = "agentProfile";
export function AgentsPanel() {
    const editContext = useEditContext();
    const searchParams = useSearchParams();
    const [state, setState] = useState("loading");
    const [installedAgents, setInstalledAgents] = useState([]);
    const [error, setError] = useState(null);
    const [searchQuery, setSearchQuery] = useState("");
    const [refreshToken, setRefreshToken] = useState(0);
    const [showAddDialog, setShowAddDialog] = useState(false);
    const [urlSelectedAgentId, setUrlSelectedAgentId] = useState(searchParams.get(SELECTED_AGENT_QUERY_PARAM) ||
        (typeof window !== "undefined"
            ? new URLSearchParams(window.location.search).get(SELECTED_AGENT_QUERY_PARAM)
            : null));
    const [selectedAgent, setSelectedAgent] = useState(null);
    const loadData = useCallback(async () => {
        try {
            setState("loading");
            setError(null);
            const installed = await setupWizardService.getInstalledAgents();
            setInstalledAgents(installed);
            setState("success");
        }
        catch (e) {
            setState("error");
            setError(e?.message || "Failed to load agent profiles");
        }
    }, []);
    useEffect(() => {
        void loadData();
    }, [loadData]);
    useEffect(() => {
        const selectedFromUrl = searchParams.get(SELECTED_AGENT_QUERY_PARAM) ||
            (typeof window !== "undefined"
                ? new URLSearchParams(window.location.search).get(SELECTED_AGENT_QUERY_PARAM)
                : null);
        setUrlSelectedAgentId(selectedFromUrl);
    }, [searchParams]);
    useEffect(() => {
        if (typeof window === "undefined")
            return;
        const handleLocationChange = () => {
            setUrlSelectedAgentId(new URLSearchParams(window.location.search).get(SELECTED_AGENT_QUERY_PARAM));
        };
        window.addEventListener("popstate", handleLocationChange);
        return () => window.removeEventListener("popstate", handleLocationChange);
    }, []);
    useEffect(() => {
        if (!urlSelectedAgentId) {
            if (selectedAgent) {
                setSelectedAgent(null);
            }
            return;
        }
        const matchingAgent = installedAgents.find((agent) => agent.id === urlSelectedAgentId);
        if (!matchingAgent) {
            return;
        }
        if (selectedAgent?.id !== matchingAgent.id ||
            selectedAgent.name !== matchingAgent.name ||
            selectedAgent.key !== matchingAgent.key) {
            setSelectedAgent({
                id: matchingAgent.id,
                name: matchingAgent.name,
                key: matchingAgent.key,
            });
        }
    }, [installedAgents, selectedAgent, urlSelectedAgentId]);
    const updateSelectedAgentUrl = useCallback((agentId) => {
        editContext?.updateUrl({
            [SELECTED_AGENT_QUERY_PARAM]: agentId || undefined,
        });
        setUrlSelectedAgentId(agentId || null);
    }, [editContext]);
    const handleSelectAgent = useCallback((agent) => {
        setSelectedAgent({
            id: agent.id,
            name: agent.name,
            key: agent.key,
        });
        updateSelectedAgentUrl(agent.id);
    }, [updateSelectedAgentUrl]);
    const handleCloseSelectedAgent = useCallback(() => {
        setSelectedAgent(null);
        updateSelectedAgentUrl(null);
    }, [updateSelectedAgentUrl]);
    const filteredAgents = useMemo(() => {
        const query = searchQuery.trim().toLowerCase();
        const sorted = [...installedAgents].sort((a, b) => (a.name ?? "").localeCompare(b.name ?? ""));
        if (!query) {
            return sorted;
        }
        return sorted.filter((agent) => {
            return (agent.name?.toLowerCase().includes(query) ||
                agent.key?.toLowerCase().includes(query) ||
                agent.description?.toLowerCase().includes(query) ||
                agent.defaultModel?.toLowerCase().includes(query));
        });
    }, [installedAgents, searchQuery]);
    const statusCounts = useMemo(() => {
        const needsConfig = installedAgents.filter((agent) => agent.needsConfiguration).length;
        return {
            installed: installedAgents.length,
            needsConfig,
        };
    }, [installedAgents]);
    const agentsListContent = (_jsx("div", { className: "h-full overflow-auto p-4", children: _jsxs("div", { className: "flex h-full flex-col overflow-hidden", children: [_jsxs("div", { className: "shrink-0 space-y-4 pb-4", children: [_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsxs("div", { className: "flex items-center gap-2 text-sm text-gray-700", children: [state === "success" ? (_jsx(CheckCircle, { className: "h-4 w-4 text-green-600", strokeWidth: 1 })) : state === "error" ? (_jsx(AlertCircle, { className: "h-4 w-4 text-red-600", strokeWidth: 1 })) : (_jsx(RefreshCw, { className: "h-4 w-4 animate-spin text-amber-600", strokeWidth: 1 })), _jsxs("span", { children: [statusCounts.installed, " agent profile", statusCounts.installed !== 1 ? "s" : "", statusCounts.needsConfig > 0 && (_jsxs("span", { className: "ml-1 text-orange-600", children: ["(", statusCounts.needsConfig, " need config)"] }))] })] }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsxs(Button, { size: "sm", variant: "outline", onClick: () => setShowAddDialog(true), disabled: state === "loading", "data-testid": "agents-panel-add-profiles", children: [_jsx(Plus, { className: "h-4 w-4", strokeWidth: 1.5 }), "Add"] }), _jsx(Button, { size: "sm", variant: "ghost", onClick: loadData, disabled: state === "loading", children: _jsx(RefreshCw, { className: `h-4 w-4 ${state === "loading" ? "animate-spin" : ""}`, strokeWidth: 1 }) })] })] }), _jsxs("div", { className: "relative", children: [_jsx(Search, { className: "absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400", strokeWidth: 1.5 }), _jsx(Input, { type: "text", placeholder: "Search agent profiles...", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), className: "pl-9" })] }), error && (_jsx("div", { className: "rounded border border-red-200 bg-red-50 p-2 text-xs whitespace-pre-wrap text-red-700", children: error }))] }), _jsx("div", { className: "min-h-0 flex-1 overflow-y-auto", children: installedAgents.length === 0 && state === "success" ? (_jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [_jsx(SecretAgentIcon, { size: 48, strokeWidth: 1, className: "mb-4 text-gray-300" }), _jsx("p", { className: "text-sm text-gray-500", children: "No agent profiles found" })] })) : filteredAgents.length === 0 && searchQuery ? (_jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [_jsx(Search, { size: 48, strokeWidth: 1, className: "mb-4 text-gray-300" }), _jsx("p", { className: "text-sm text-gray-500", children: "No agent profiles match your search" })] })) : (_jsx("div", { className: "space-y-3", children: filteredAgents.map((agent) => {
                            const isSelected = selectedAgent?.id === agent.id;
                            return (_jsx("button", { type: "button", onClick: () => handleSelectAgent(agent), className: `w-full rounded-lg border p-4 text-left transition-shadow hover:shadow-sm ${isSelected
                                    ? "border-blue-400 bg-blue-50"
                                    : "border-gray-200 bg-white"}`, children: _jsxs("div", { className: "flex items-start gap-3", children: [_jsx("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center", children: _jsx(SecretAgentIcon, { size: 20, strokeWidth: 1.5, className: "text-gray-600" }) }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("h4", { className: "font-medium text-gray-900", children: agent.name }), agent.isMandatory && (_jsxs("span", { className: "flex items-center gap-1 rounded bg-purple-100 px-1.5 py-0.5 text-xs font-medium text-purple-700", children: [_jsx(Shield, { className: "h-3 w-3", strokeWidth: 1.5 }), "Required"] })), agent.needsConfiguration && (_jsx("span", { className: "rounded bg-orange-100 px-2 py-0.5 text-xs font-medium text-orange-700", children: "Needs Config" }))] }), (agent.defaultModel || agent.description) && (_jsxs("div", { className: "mt-2 space-y-1 text-xs text-gray-600", children: [agent.defaultModel && (_jsxs("div", { children: [_jsx("span", { className: "font-medium", children: "Default Model:" }), " ", _jsx("span", { className: "text-gray-700", children: agent.defaultModel })] })), agent.description && (_jsxs("div", { className: "line-clamp-2", children: [_jsx("span", { className: "font-medium", children: "Description:" }), " ", _jsx("span", { className: "text-gray-700", children: agent.description })] }))] }))] }), _jsxs("div", { className: `inline-flex shrink-0 items-center gap-2 rounded-md px-3 py-2 text-sm ${isSelected
                                                ? "bg-black text-white"
                                                : "text-gray-700"}`, children: [_jsx(Settings, { className: "h-4 w-4", strokeWidth: 1.5 }), "Configure"] })] }) }, agent.id));
                        }) })) })] }) }));
    const panels = selectedAgent
        ? [
            {
                name: "agents-list",
                defaultSize: "auto",
                content: agentsListContent,
                className: "overflow-hidden",
            },
            {
                name: "agent-config",
                defaultSize: 420,
                content: (_jsx(AgentProfileEditorPanel, { agent: selectedAgent, refreshToken: refreshToken, onClose: handleCloseSelectedAgent }, `${selectedAgent.id}:${refreshToken}`)),
                className: "overflow-hidden",
            },
        ]
        : [
            {
                name: "agents-list",
                defaultSize: "auto",
                content: agentsListContent,
                className: "overflow-hidden",
            },
        ];
    return (_jsxs(_Fragment, { children: [_jsx(CreateAgentProfileDialog, { open: showAddDialog, onOpenChange: setShowAddDialog, onCreated: async (agentId) => {
                    await loadData();
                    setRefreshToken((c) => c + 1);
                    updateSelectedAgentUrl(agentId);
                } }), _jsx(Splitter, { panels: panels, localStorageKey: "settings-agents-panel-splitter", direction: "horizontal", className: "h-full" })] }));
}
export default AgentsPanel;
//# sourceMappingURL=AgentsPanel.js.map