import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import ZodSchemaForm, { lightTheme, darkTheme } from 'zod-schema-form';
import DeleteServerButton from './DeleteServerButton';
import StatusPill from './StatusPill';
import DashboardStat from './DashboardStat';
import Accordion from './core/Accordion';
import { useTheme, useThemeName } from '../theme';
import { stringifyPromptContent } from '../lib/promptUtils';
const ServerDashboardView = ({ options, tools, serverEnabled, onToggleServer, onEdit, onRefresh, onDelete, onViewTool, getToolPermission, onChangeToolPermission, headers, autoFetchEnabled, inlineToolView = false, serverInfo, protocolVersion, capabilities, lastEvent, isLoadingTools, prompts, promptsError, isLoadingPrompts, onRefreshPrompts, onRunPrompt, supportsPromptExecution, showTools = true, showStats = true, showPrompts = true }) => {
    const theme = useTheme();
    const dashboardTheme = theme.serverDashboard;
    const toolSectionTheme = dashboardTheme.toolSection;
    const promptSectionTheme = dashboardTheme.promptSection;
    const themeName = useThemeName();
    const headerCount = Object.keys(headers).length;
    const toolCountLabel = `${tools.length} ${tools.length === 1 ? 'tool' : 'tools'}`;
    const promptCountLabel = `${prompts.length} ${prompts.length === 1 ? 'prompt' : 'prompts'}`;
    const containerClasses = showStats ? dashboardTheme.container : dashboardTheme.toolsOnlyContainer;
    const sectionsSpacingClass = showStats ? toolSectionTheme.container : toolSectionTheme.toolsOnlyContainer;
    const toolSectionTitle = showStats ? 'Tool access' : 'Tools';
    const showToolToggle = showStats;
    const resolvedServerName = serverInfo?.name ?? options.serverName;
    const resolvedServerVersion = serverInfo?.version;
    const capabilityCount = capabilities ? Object.keys(capabilities).length : 0;
    const lastEventTimestamp = lastEvent ? new Date(lastEvent.receivedAt).toLocaleString() : null;
    const lastEventParams = lastEvent?.message.params;
    const hasLastEventParams = lastEventParams !== undefined && lastEventParams !== null;
    const [promptStates, setPromptStates] = React.useState({});
    const shouldRenderTools = showTools;
    const shouldRenderPrompts = showPrompts;
    React.useEffect(() => {
        setPromptStates((prev) => {
            const next = {};
            for (const prompt of prompts) {
                const existing = prev[prompt.name];
                if (existing) {
                    next[prompt.name] = existing;
                }
            }
            return next;
        });
    }, [prompts]);
    const handlePromptSubmit = React.useCallback(async (promptName, values) => {
        const normalizedArgs = Object.fromEntries(Object.entries(values ?? {}));
        if (!onRunPrompt) {
            setPromptStates((prev) => ({
                ...prev,
                [promptName]: {
                    status: 'error',
                    error: 'Prompt execution is not supported in this environment.',
                    output: undefined,
                    lastArgs: values
                }
            }));
            return;
        }
        setPromptStates((prev) => ({
            ...prev,
            [promptName]: {
                status: 'loading',
                error: undefined,
                output: undefined,
                lastArgs: values
            }
        }));
        try {
            const result = await onRunPrompt(promptName, normalizedArgs);
            setPromptStates((prev) => ({
                ...prev,
                [promptName]: result.error
                    ? {
                        status: 'error',
                        error: result.error instanceof Error ? result.error.message : String(result.error),
                        output: result.prompt,
                        lastArgs: values
                    }
                    : {
                        status: 'success',
                        error: undefined,
                        output: result.prompt,
                        lastArgs: values
                    }
            }));
        }
        catch (error) {
            setPromptStates((prev) => ({
                ...prev,
                [promptName]: {
                    status: 'error',
                    error: error instanceof Error ? error.message : 'Failed to fetch prompt output.',
                    output: undefined,
                    lastArgs: values
                }
            }));
        }
    }, [onRunPrompt]);
    return (_jsxs("div", { className: containerClasses, children: [_jsx("div", { className: dashboardTheme.headerRow, children: _jsx("div", { className: dashboardTheme.headerInfoGroup, children: !showStats ? (_jsxs(_Fragment, { children: [_jsx("p", { className: dashboardTheme.serverName, children: resolvedServerName }), _jsx("p", { className: dashboardTheme.serverUrl, children: options.url })] })) : (_jsx("span", { className: dashboardTheme.headerViewLabel, children: "View mode" })) }) }), showStats && (_jsxs(_Fragment, { children: [_jsxs("header", { className: theme.serverTitle.container, children: [_jsxs("div", { className: 'flex-1', children: [_jsxs("div", { className: 'flex flex-wrap items-center gap-3', children: [_jsx("h3", { className: theme.serverTitle.title, children: resolvedServerName }), _jsx(StatusPill, { tone: 'accent', children: "MCP Server" }), _jsx(StatusPill, { tone: 'success', children: "Connected" }), serverEnabled ? _jsx(StatusPill, { tone: 'enabled', children: "Enabled" }) : _jsx(StatusPill, { tone: 'muted', children: "Disabled" })] }), _jsx("p", { className: dashboardTheme.serverUrlDetail, children: options.url }), resolvedServerVersion && (_jsxs("p", { className: dashboardTheme.serverVersion, children: ["Server version: ", resolvedServerVersion] }))] }), _jsxs("div", { className: 'flex flex-col items-end gap-3 sm:flex-row sm:items-center', children: [_jsxs("label", { className: dashboardTheme.toggleLabel, children: [_jsx("input", { type: 'checkbox', className: dashboardTheme.toggleCheckbox, checked: serverEnabled, onChange: (event) => onToggleServer(event.target.checked) }), _jsx("span", { children: serverEnabled ? 'Server enabled' : 'Enable server' })] }), _jsx("button", { onClick: onEdit, className: dashboardTheme.editButton, children: "Edit Connection" })] })] }), _jsxs("dl", { className: dashboardTheme.statsGrid, children: [_jsx(DashboardStat, { label: 'Endpoint URL', children: options.url || 'Not set' }), _jsx(DashboardStat, { label: 'Tools fetched', children: toolCountLabel }), _jsx(DashboardStat, { label: 'HTTP method', children: "POST" }), _jsx(DashboardStat, { label: 'Protocol version', children: protocolVersion ?? 'Not reported' }), _jsx(DashboardStat, { label: 'Server capabilities', children: capabilityCount > 0 ? `${capabilityCount} ${capabilityCount === 1 ? 'category' : 'categories'}` : 'None' }), _jsx(DashboardStat, { label: 'Auto fetch', children: autoFetchEnabled ? 'Enabled' : 'Manual' }), _jsx(DashboardStat, { label: 'Custom headers', children: headerCount > 0 ? `${headerCount} ${headerCount === 1 ? 'header' : 'headers'}` : 'None' }), lastEvent && (_jsx(DashboardStat, { label: 'Latest notification', children: _jsxs("div", { className: 'space-y-1', children: [_jsx("span", { className: dashboardTheme.lastEventMethod, children: lastEvent.message.method }), lastEventTimestamp && (_jsx("span", { className: dashboardTheme.lastEventTimestamp, children: lastEventTimestamp })), hasLastEventParams && (_jsx("pre", { className: dashboardTheme.lastEventPayload, children: String(JSON.stringify(lastEventParams, null, 2)) }))] }) }))] })] })), (shouldRenderTools || shouldRenderPrompts) && (_jsxs("div", { className: sectionsSpacingClass, children: [shouldRenderTools && (_jsx(Accordion, { defaultOpen: !showStats, header: (_jsxs("div", { className: `${toolSectionTheme.header} w-full`, children: [_jsx("span", { className: toolSectionTheme.title, children: toolSectionTitle }), _jsx("span", { className: toolSectionTheme.count, children: toolCountLabel })] })), children: _jsxs("div", { className: toolSectionTheme.container, children: [_jsx("div", { className: 'flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end', children: _jsx("button", { type: 'button', onClick: onRefresh, className: toolSectionTheme.refreshButton, disabled: isLoadingTools, children: isLoadingTools ? 'Refreshing…' : 'Refresh tools' }) }), tools.length > 0 ? (_jsx("ul", { className: toolSectionTheme.list, children: tools.map((tool) => {
                                        const permission = getToolPermission(tool.name);
                                        const enabled = permission === 'enabled';
                                        const permissionLabel = permission === 'disabled'
                                            ? 'Disabled'
                                            : permission === 'ask_first'
                                                ? 'Ask first'
                                                : null;
                                        const permissionFieldId = `tool-permission-${tool.name.replace(/[^a-z0-9_-]/gi, '_')}`;
                                        const listItemClassName = showToolToggle ? toolSectionTheme.listItemWithToggle : toolSectionTheme.listItem;
                                        return (_jsxs("li", { className: listItemClassName, children: [_jsxs("div", { className: 'flex-1', children: [_jsxs("div", { className: 'flex flex-wrap items-center gap-2', children: [_jsx("button", { type: 'button', onClick: () => onViewTool(tool), className: toolSectionTheme.toolNameButton, children: tool.name }), permissionLabel && (_jsx("span", { className: toolSectionTheme.toolDisabledBadge, children: permissionLabel }))] }), tool.description && _jsx("p", { className: toolSectionTheme.toolDescription, children: tool.description })] }), showToolToggle && (_jsx("div", { className: 'flex flex-col gap-1 text-right sm:items-end', children: _jsxs("select", { id: permissionFieldId, className: toolSectionTheme.toggleSelect, value: permission, onChange: (event) => {
                                                            const nextPermission = event.target.value;
                                                            onChangeToolPermission(tool.name, nextPermission);
                                                        }, children: [_jsx("option", { value: 'enabled', children: "Enabled" }), _jsx("option", { value: 'ask_first', children: "Ask first" }), _jsx("option", { value: 'disabled', children: "Disabled" })] }) }))] }, tool.name));
                                    }) })) : isLoadingTools ? (_jsx("p", { className: toolSectionTheme.loadingState, children: "Loading tools from the server\u2026" })) : (_jsx("p", { className: toolSectionTheme.emptyState, children: "No tools available for this server yet. Refresh the connection or adjust server settings." }))] }) })), shouldRenderPrompts && (_jsx(Accordion, { defaultOpen: !showStats && prompts.length > 0, header: (_jsxs("div", { className: `${promptSectionTheme.header} w-full`, children: [_jsx("span", { className: promptSectionTheme.title, children: "Prompts" }), _jsx("span", { className: promptSectionTheme.count, children: promptCountLabel })] })), children: _jsxs("div", { className: promptSectionTheme.container, children: [_jsx("div", { className: 'flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end', children: _jsx("button", { type: 'button', onClick: () => {
                                            void onRefreshPrompts();
                                        }, className: promptSectionTheme.refreshButton, disabled: isLoadingPrompts, children: isLoadingPrompts ? 'Refreshing…' : 'Refresh prompts' }) }), promptsError && (_jsx("div", { className: promptSectionTheme.alertError, children: promptsError })), !supportsPromptExecution && (_jsx("div", { className: promptSectionTheme.alertWarning, children: "Prompt execution is unavailable with the current MCP client. Update the integration to enable previewing prompt output." })), prompts.length > 0 ? (_jsx("ul", { className: promptSectionTheme.list, children: prompts.map((prompt) => {
                                        const state = promptStates[prompt.name];
                                        const isRunningPrompt = state?.status === 'loading';
                                        const schema = (prompt.arguments ?? []).map((arg) => [
                                            arg.name,
                                            {
                                                type: 'string',
                                                label: arg.name,
                                                description: arg.description,
                                                required: arg.required ?? false
                                            }
                                        ]);
                                        return (_jsxs("li", { className: promptSectionTheme.card, children: [_jsxs("div", { className: promptSectionTheme.cardHeader, children: [_jsx("h4", { className: promptSectionTheme.cardTitle, children: prompt.name }), prompt.description && (_jsx("p", { className: promptSectionTheme.cardDescription, children: prompt.description }))] }), prompt.arguments && prompt.arguments.length > 0 ? (_jsxs("div", { children: [_jsx("h5", { className: promptSectionTheme.argumentsHeading, children: "Arguments" }), _jsx("ul", { className: promptSectionTheme.argumentList, children: prompt.arguments.map((arg) => (_jsxs("li", { className: promptSectionTheme.argumentItem, children: [_jsx("span", { className: promptSectionTheme.argumentName, children: arg.name }), arg.required && (_jsx("span", { className: promptSectionTheme.argumentRequiredBadge, children: "Required" })), arg.description && _jsx("span", { className: promptSectionTheme.argumentDescription, children: arg.description })] }, arg.name))) })] })) : (_jsx("p", { className: promptSectionTheme.argumentEmpty, children: "No arguments required." })), _jsxs("div", { className: promptSectionTheme.executionSection, children: [_jsx("h5", { className: promptSectionTheme.executionHeading, children: "Get prompt output" }), _jsx(ZodSchemaForm, { schema: schema, initialValues: state?.lastArgs, onSubmit: (formValues) => handlePromptSubmit(prompt.name, formValues), submitButtonText: isRunningPrompt ? 'Running…' : 'Get prompt output', size: 'small', theme: themeName === 'dark' ? darkTheme : lightTheme, isSubmitting: isRunningPrompt }, `${prompt.name}-form`), isRunningPrompt && (_jsx("div", { className: promptSectionTheme.executionInfo, children: "Requesting prompt output\u2026" })), state?.status === 'error' && state.error && (_jsx("div", { className: promptSectionTheme.executionError, children: state.error })), state?.status === 'success' && (_jsxs("div", { className: promptSectionTheme.successContainer, children: [state.output?.messages && state.output.messages.length > 0 ? (_jsx("div", { className: 'space-y-2', children: state.output.messages.map((message, index) => {
                                                                        const messageText = stringifyPromptContent(message.content);
                                                                        return (_jsxs("div", { className: promptSectionTheme.resultMessageCard, children: [_jsx("div", { className: promptSectionTheme.resultMessageRole, children: message.role ?? 'assistant' }), _jsx("div", { className: promptSectionTheme.resultMessageBody, children: messageText || 'This message did not include text content.' })] }, `${prompt.name}-message-${index}`));
                                                                    }) })) : (_jsx("div", { className: promptSectionTheme.resultEmpty, children: "Prompt returned no messages." })), _jsxs("details", { className: promptSectionTheme.rawDetails, children: [_jsx("summary", { className: promptSectionTheme.rawDetailsSummary, children: "Raw prompt payload" }), _jsx("pre", { className: promptSectionTheme.rawDetailsPre, children: JSON.stringify(state.output ?? null, null, 2) })] })] }))] })] }, prompt.name));
                                    }) })) : isLoadingPrompts ? (_jsx("p", { className: promptSectionTheme.loadingState, children: "Loading prompts from the server\u2026" })) : (_jsx("p", { className: promptSectionTheme.emptyState, children: "No prompts available for this server yet. Trigger a refresh once prompts are configured." }))] }) }))] })), showStats && (_jsx("div", { className: dashboardTheme.footer, children: _jsx(DeleteServerButton, { onClick: onDelete, variant: 'solid' }) }))] }));
};
export default ServerDashboardView;
