import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useMemo } from "react";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { Button } from "../../../components/ui/button";
import { Card } from "../../../components/ui/card";
import { SettingsPanelLayout } from "../SettingsPanelLayout";
import { CreateMcpServerDialog } from "./CreateMcpServerDialog";
import { useRequiredSettingsHeaderActions } from "../SettingsHeaderActionsContext";
import { CheckCircle, AlertCircle, RefreshCw, Download, ChevronDown, ChevronRight, Server, Plus, } from "lucide-react";
const getErrorMessage = (error, fallback) => error instanceof Error ? error.message : fallback;
/**
 * Settings panel for viewing installed MCP Tools.
 * Displays MCP tool functions from the GetMcpToolFunctions endpoint.
 */
export function McpToolsPanel() {
    const setSettingsHeaderActions = useRequiredSettingsHeaderActions();
    const [state, setState] = useState("loading");
    const [tools, setTools] = useState([]);
    const [error, setError] = useState(null);
    const [installing, setInstalling] = useState(false);
    const [installResult, setInstallResult] = useState(null);
    const [installError, setInstallError] = useState(null);
    const [createServerOpen, setCreateServerOpen] = useState(false);
    const [createServerResult, setCreateServerResult] = useState(null);
    const [collapsedServers, setCollapsedServers] = useState(new Set());
    // Group tools by server name
    const toolsByServer = useMemo(() => {
        const groups = {};
        for (const tool of tools) {
            const serverName = tool.serverName || "Unknown Server";
            if (!groups[serverName]) {
                groups[serverName] = [];
            }
            groups[serverName].push(tool);
        }
        return groups;
    }, [tools]);
    const serverNames = useMemo(() => Object.keys(toolsByServer).sort(), [toolsByServer]);
    const toggleServer = (serverName) => {
        setCollapsedServers((prev) => {
            const next = new Set(prev);
            if (next.has(serverName)) {
                next.delete(serverName);
            }
            else {
                next.add(serverName);
            }
            return next;
        });
    };
    const loadData = async () => {
        try {
            setState("loading");
            setError(null);
            setInstallResult(null);
            setInstallError(null);
            const toolsData = await setupWizardService.getMcpToolFunctions();
            setTools(toolsData);
            setState("success");
        }
        catch (e) {
            setState("error");
            setError(getErrorMessage(e, "Failed to load MCP tools"));
        }
    };
    const handleServerCreated = async (_serverId, serverName) => {
        setCreateServerResult(`MCP server "${serverName}" created`);
        await loadData();
    };
    const handleInstall = async () => {
        try {
            setInstalling(true);
            setInstallError(null);
            setInstallResult(null);
            setCreateServerResult(null);
            const result = await setupWizardService.installMcpTools();
            // Build result message
            const messages = [];
            if (result.newToolsDiscoveredCount > 0) {
                messages.push(`${result.newToolsDiscoveredCount} new tool${result.newToolsDiscoveredCount !== 1 ? "s" : ""} installed`);
            }
            if (result.updatedCount > 0) {
                messages.push(`${result.updatedCount} tool${result.updatedCount !== 1 ? "s" : ""} updated`);
            }
            // Only report "No new tools found" when the install actually
            // succeeded — if every server errored, the error banner tells the
            // real story and a green "all good" message would contradict it.
            if (messages.length === 0 && result.errors.length === 0) {
                messages.push("No new tools found");
            }
            setInstallResult(messages.length > 0 ? messages.join(", ") : null);
            if (result.errors.length > 0) {
                setInstallError(result.errors.join("\n"));
            }
            // Reload the tools list (but preserve install messages)
            const toolsData = await setupWizardService.getMcpToolFunctions();
            setTools(toolsData);
            setState("success");
        }
        catch (e) {
            setInstallError(getErrorMessage(e, "Failed to install MCP tools"));
        }
        finally {
            setInstalling(false);
        }
    };
    useEffect(() => {
        loadData();
    }, []);
    const addMcpServerButton = useMemo(() => (_jsxs(Button, { size: "sm", variant: "default", onClick: () => setCreateServerOpen(true), disabled: state === "loading" || installing, title: "Add MCP server", children: [_jsx(Plus, { className: "mr-1 h-4 w-4", strokeWidth: 1.75 }), "Add MCP server"] })), [state, installing]);
    // Surface the primary "Add" action in the settings header bar (desktop only;
    // a mobile fallback lives in the card header below).
    useEffect(() => {
        if (!setSettingsHeaderActions)
            return;
        setSettingsHeaderActions(addMcpServerButton);
        return () => {
            setSettingsHeaderActions(null);
        };
    }, [addMcpServerButton, setSettingsHeaderActions]);
    return (_jsxs(SettingsPanelLayout, { children: [_jsx(Card, { icon: _jsx(Server, { strokeWidth: 1, className: "h-5 w-5" }), title: _jsxs(_Fragment, { children: ["MCP tools", " ", _jsxs("span", { className: "text-neutral-grey-50 font-normal", children: ["(", tools.length, ")"] })] }), description: "Tools exposed by connected MCP servers, assignable like any other tool.", headerActions: _jsxs("div", { className: "flex items-center gap-1", children: [_jsx("div", { className: "md:hidden", children: addMcpServerButton }), _jsxs(Button, { size: "sm", variant: "outline", onClick: handleInstall, disabled: installing || state === "loading", title: "Install MCP Tools", children: [installing ? (_jsx(RefreshCw, { className: "h-4 w-4 animate-spin", strokeWidth: 1 })) : (_jsx(Download, { className: "h-4 w-4", strokeWidth: 1 })), _jsx("span", { className: "ml-1 hidden sm:inline", children: installing ? "Installing..." : "Install MCP Tools" })] })] }), children: _jsxs("div", { className: "space-y-4", children: [installResult && (_jsx("div", { className: "border-feedback-green bg-feedback-green-light text-feedback-green rounded border p-3 text-sm", children: installResult })), createServerResult && (_jsx("div", { className: "border-feedback-green bg-feedback-green-light text-feedback-green rounded border p-3 text-sm", children: createServerResult })), installError && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded border p-3 text-sm whitespace-pre-wrap", children: installError })), tools.length === 0 && state === "success" && !installError && (_jsxs("div", { className: "flex flex-col items-center justify-center px-6 py-12 text-center", children: [_jsx(Server, { className: "text-neutral-grey-50 mb-4 h-10 w-10", strokeWidth: 1.25 }), _jsx("p", { className: "text-neutral-grey-50 text-sm font-medium", children: "No MCP tools installed" }), _jsx("p", { className: "text-neutral-grey-50 mt-1 text-xs", children: "MCP tools can be added via the Sitecore content tree." })] })), tools.length > 0 && (_jsx("div", { className: "space-y-3", children: serverNames.map((serverName) => {
                                const serverTools = toolsByServer[serverName] ?? [];
                                const isCollapsed = collapsedServers.has(serverName);
                                return (_jsxs("div", { className: "border-border-default overflow-hidden rounded-lg border", children: [_jsxs("button", { onClick: () => toggleServer(serverName), className: "bg-neutral-grey-5 text-neutral-grey-100 hover:bg-neutral-grey-5 flex w-full items-center gap-2 px-3 py-2 text-left text-sm font-medium transition-colors", children: [isCollapsed ? (_jsx(ChevronRight, { className: "text-neutral-grey-50 h-4 w-4 shrink-0", strokeWidth: 1.5 })) : (_jsx(ChevronDown, { className: "text-neutral-grey-50 h-4 w-4 shrink-0", strokeWidth: 1.5 })), _jsx(Server, { className: "text-neutral-grey-50 h-4 w-4 shrink-0", strokeWidth: 1.5 }), _jsx("span", { className: "min-w-0 truncate", children: serverName }), _jsxs("span", { className: "text-neutral-grey-50 ml-auto shrink-0 text-xs font-normal", children: [serverTools.length, " tool", serverTools.length !== 1 ? "s" : ""] })] }), !isCollapsed && (_jsx("div", { className: "divide-border-default divide-y", children: serverTools.map((tool) => (_jsxs("div", { className: "flex flex-wrap items-center gap-2 bg-white px-3 py-2 text-sm", children: [_jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("span", { className: "font-normal", children: tool.functionName }), tool.description && (_jsx("p", { className: "text-neutral-grey-50 mt-0.5 line-clamp-2 text-xs sm:line-clamp-none sm:truncate", children: tool.description }))] }), _jsxs("div", { className: "flex shrink-0 flex-wrap items-center gap-1", children: [tool.isInstalled ? (_jsxs("span", { className: "rounded-badge bg-feedback-green-light badge-pad-sm text-2xs text-feedback-green inline-flex items-center gap-1", title: "Installed", children: [_jsx(CheckCircle, { className: "h-3 w-3", strokeWidth: 1.5 }), _jsx("span", { className: "hidden sm:inline", children: "Installed" })] })) : (_jsx("span", { className: "rounded-badge bg-neutral-grey-5 badge-pad-sm text-2xs text-neutral-grey-50 inline-flex items-center gap-1", children: "Not installed" })), tool.needsConfiguration && (_jsxs("span", { className: "rounded-badge bg-feedback-orange-light badge-pad-sm text-2xs text-feedback-orange inline-flex items-center gap-1", title: "Needs configuration", children: [_jsx(AlertCircle, { className: "h-3 w-3", strokeWidth: 1.5 }), _jsx("span", { className: "hidden sm:inline", children: "Needs config" })] }))] })] }, tool.functionName))) }))] }, serverName));
                            }) })), error && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded border p-2 text-xs whitespace-pre-wrap", children: error }))] }) }), _jsx(CreateMcpServerDialog, { open: createServerOpen, onOpenChange: setCreateServerOpen, onCreated: handleServerCreated })] }));
}
export default McpToolsPanel;
//# sourceMappingURL=McpToolsPanel.js.map