import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useMemo } from "react";
import { setupWizardService, } from "../../../setup/services/setupWizardService";
import { Button } from "../../../components/ui/button";
import { CheckCircle, AlertCircle, RefreshCw, Download, ChevronDown, ChevronRight, Server, } from "lucide-react";
/**
 * Settings panel for viewing installed MCP Tools.
 * Displays MCP tool functions from the GetMcpToolFunctions endpoint.
 */
export function McpToolsPanel() {
    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 [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(e?.message || "Failed to load MCP tools");
        }
    };
    const handleInstall = async () => {
        try {
            setInstalling(true);
            setInstallError(null);
            setInstallResult(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`);
            }
            if (messages.length === 0) {
                messages.push("No new tools found");
            }
            setInstallResult(messages.join(", "));
            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(e?.message || "Failed to install MCP tools");
        }
        finally {
            setInstalling(false);
        }
    };
    useEffect(() => {
        loadData();
    }, []);
    const statusIcon = (currentState) => {
        if (currentState === "success")
            return _jsx(CheckCircle, { className: "h-4 w-4 text-green-600", strokeWidth: 1 });
        if (currentState === "error")
            return _jsx(AlertCircle, { className: "h-4 w-4 text-red-600", strokeWidth: 1 });
        return (_jsx(RefreshCw, { className: "h-4 w-4 animate-spin text-amber-600", strokeWidth: 1 }));
    };
    return (_jsx("div", { className: "h-full overflow-auto p-4", children: _jsx("div", { className: "mx-auto", children: _jsx("div", { className: "rounded-lg bg-white p-4 md:p-6", children: _jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsxs("div", { className: "flex flex-1 items-center gap-2", children: [statusIcon(state), _jsxs("span", { className: "text-sm text-gray-700", children: [tools.length, " MCP tool", tools.length !== 1 ? "s" : "", " ", "installed"] })] }), _jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [_jsxs("button", { onClick: loadData, disabled: state === "loading" || installing, className: "flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 disabled:opacity-50", title: "Refresh tools list", children: [_jsx(RefreshCw, { className: `h-4 w-4 ${state === "loading" ? "animate-spin" : ""}`, strokeWidth: 1 }), _jsx("span", { className: "hidden sm:inline", children: "Refresh" })] }), _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" })] })] })] }), installResult && (_jsx("div", { className: "rounded border border-green-200 bg-green-50 p-3 text-sm text-green-800", children: installResult })), installError && (_jsx("div", { className: "rounded border border-red-200 bg-red-50 p-3 text-sm whitespace-pre-wrap text-red-700", children: installError })), tools.length === 0 && state === "success" && (_jsx("div", { className: "rounded border border-yellow-200 bg-yellow-50 p-3 text-sm text-yellow-800", children: "No MCP tools are installed. 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: "overflow-hidden rounded-lg border border-gray-200", children: [_jsxs("button", { onClick: () => toggleServer(serverName), className: "flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left text-sm font-medium text-gray-700 transition-colors hover:bg-gray-100", children: [isCollapsed ? (_jsx(ChevronRight, { className: "h-4 w-4 shrink-0 text-gray-500", strokeWidth: 1.5 })) : (_jsx(ChevronDown, { className: "h-4 w-4 shrink-0 text-gray-500", strokeWidth: 1.5 })), _jsx(Server, { className: "h-4 w-4 shrink-0 text-gray-500", strokeWidth: 1.5 }), _jsx("span", { className: "min-w-0 truncate", children: serverName }), _jsxs("span", { className: "ml-auto shrink-0 text-xs font-normal text-gray-500", children: [serverTools.length, " tool", serverTools.length !== 1 ? "s" : ""] })] }), !isCollapsed && (_jsx("div", { className: "divide-y divide-gray-100", 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-medium", children: tool.functionName }), tool.description && (_jsx("p", { className: "mt-0.5 line-clamp-2 text-xs text-gray-500 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: "inline-flex items-center gap-1 rounded-full bg-green-100 px-2 py-0.5 text-xs text-green-700", title: "Installed", children: [_jsx(CheckCircle, { className: "h-3 w-3", strokeWidth: 1.5 }), _jsx("span", { className: "hidden sm:inline", children: "Installed" })] })) : (_jsx("span", { className: "inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600", children: "Not installed" })), tool.needsConfiguration && (_jsxs("span", { className: "inline-flex items-center gap-1 rounded-full bg-amber-100 px-2 py-0.5 text-xs text-amber-700", 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: "rounded border border-red-200 bg-red-50 p-2 text-xs whitespace-pre-wrap text-red-700", children: error }))] }) }) }) }));
}
export default McpToolsPanel;
//# sourceMappingURL=McpToolsPanel.js.map