import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Plus, Search, Shield } from "lucide-react";
import { useSearchParams } from "../../client/navigation";
import { Button } from "../../../components/ui/button";
import { SettingsPanelLayout } from "../SettingsPanelLayout";
import { SearchInput } from "../../../components/SearchInput";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { useEditContext } from "../../client/editContext";
import { Splitter } from "../../ui/Splitter";
import { ParheliaAgentIcon } from "../../ui/Icons";
import { AgentProfileEditorPanel } from "./AgentProfileEditorPanel";
import { CreateAgentProfileDialog } from "./CreateAgentProfileDialog";
import { useRequiredSettingsHeaderActions } from "../SettingsHeaderActionsContext";
const SELECTED_AGENT_QUERY_PARAM = "agentProfile";
export function AgentsPanel() {
    const editContext = useEditContext();
    const setSettingsHeaderActions = useRequiredSettingsHeaderActions();
    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 ||
            selectedAgent.svgIcon !== matchingAgent.svgIcon) {
            setSelectedAgent({
                id: matchingAgent.id,
                name: matchingAgent.name,
                key: matchingAgent.key,
                svgIcon: matchingAgent.svgIcon,
            });
        }
    }, [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,
            svgIcon: agent.svgIcon,
        });
        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 addAgentButton = useMemo(() => (_jsxs(Button, { size: "sm", variant: "default", onClick: () => setShowAddDialog(true), disabled: state === "loading", "data-testid": "agents-panel-add-profiles", title: "Add agent profile", children: [_jsx(Plus, { className: "mr-1 h-4 w-4", strokeWidth: 1 }), "Add agent profile"] })), [state]);
    // Surface the primary "Add" action in the settings header bar (desktop only;
    // a mobile fallback lives in the toolbar below).
    useEffect(() => {
        if (!setSettingsHeaderActions)
            return;
        setSettingsHeaderActions(addAgentButton);
        return () => {
            setSettingsHeaderActions(null);
        };
    }, [addAgentButton, setSettingsHeaderActions]);
    const agentsListContent = (_jsx(SettingsPanelLayout, { children: _jsxs("div", { className: "overflow-hidden rounded-lg bg-white", children: [_jsxs("div", { className: "shrink-0 px-4 py-3", children: [_jsxs("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-center", children: [_jsx(SearchInput, { value: searchQuery, onChange: setSearchQuery, placeholder: "Filter by name, key, model, or description...", className: "w-full" }), _jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [statusCounts.needsConfig > 0 && (_jsxs("span", { className: "bg-component-shared-drop-zone badge-pad-sm text-component-shared shrink-0 rounded text-[10px] font-medium", children: [statusCounts.needsConfig, " need config"] })), _jsx("div", { className: "md:hidden", children: addAgentButton })] })] }), error && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red mt-2 rounded border p-2 text-xs whitespace-pre-wrap", children: error }))] }), _jsx("div", { className: "px-4 py-3", children: installedAgents.length === 0 && state === "success" ? (_jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [_jsx(ParheliaAgentIcon, { size: 48, strokeWidth: 1, className: "text-neutral-grey-50 mb-4" }), _jsx("p", { className: "text-neutral-grey-50 text-sm", 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: "text-neutral-grey-50 mb-4" }), _jsx("p", { className: "text-neutral-grey-50 text-sm", children: "No agent profiles match your search" })] })) : (_jsx("div", { className: "divide-border-default divide-y", children: filteredAgents.map((agent) => {
                            const isSelected = selectedAgent?.id === agent.id;
                            const metaSegments = [
                                agent.defaultModel,
                                agent.description,
                            ].filter(Boolean);
                            return (_jsxs("button", { type: "button", onClick: () => handleSelectAgent(agent), className: `group focus-visible:ring-feedback-blue flex w-full cursor-pointer items-center gap-3 px-3 py-3 text-left text-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-inset ${isSelected
                                    ? "bg-neutral-grey-5"
                                    : "hover:bg-neutral-grey-5 bg-white"}`, children: [_jsx(ParheliaAgentIcon, { size: 18, strokeWidth: 1, className: "text-neutral-grey-100 shrink-0" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-1.5", children: [_jsx("span", { className: "text-neutral-grey-100 truncate font-medium", children: agent.name }), agent.isMandatory && (_jsxs("span", { className: "bg-highlight-10 badge-pad-sm text-highlight-100 flex shrink-0 items-center gap-0.5 rounded text-[10px] font-medium", children: [_jsx(Shield, { className: "h-2.5 w-2.5", strokeWidth: 1 }), "Required"] })), agent.needsConfiguration && (_jsx("span", { className: "bg-component-shared-drop-zone badge-pad-sm text-component-shared shrink-0 rounded text-[10px] font-medium", children: "Needs config" }))] }), metaSegments.length > 0 && (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", children: metaSegments.join(" · ") }))] })] }, 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