import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { ViewTabs } from './ViewTabs';
import { useMcpServers } from '../contexts/McpContext';
import { useTheme } from '../theme';
import { useMcp } from 'react-mcp-hook';
export const McpPromptsView = ({ activeView, onSelectView, onOpenSettings }) => {
    const { servers } = useMcpServers();
    const theme = useTheme();
    return (_jsxs("div", { className: theme.mcpToolsView.container, children: [_jsx("div", { className: theme.mcpToolsView.header, children: _jsxs("div", { className: theme.mcpToolsView.headerInner, children: [_jsx(ViewTabs, { activeView: activeView, onSelectView: onSelectView }), onOpenSettings && (_jsx("button", { type: 'button', onClick: onOpenSettings, className: theme.mcpToolsView.settingsButton, children: "Settings" }))] }) }), _jsx("div", { className: theme.mcpToolsView.body, children: _jsxs("div", { className: 'space-y-4', children: [servers.map(({ id }) => (_jsx(PromptServerCard, { serverId: id }, id))), servers.length === 0 && (_jsxs("div", { className: theme.mcpToolsView.serverEmptyState, children: ["No MCP servers configured yet. Open ", _jsx("span", { className: 'font-medium text-gray-700', children: "Settings" }), " to connect a server before browsing prompts here."] }))] }) })] }));
};
const PromptServerCard = ({ serverId }) => {
    const { getServer } = useMcpServers();
    const theme = useTheme();
    const server = getServer(serverId);
    const connectionOptions = React.useMemo(() => {
        if (!server || server.serverEnabled === false) {
            return null;
        }
        const url = typeof server.url === 'string' ? server.url.trim() : '';
        if (!url) {
            return null;
        }
        return {
            url,
            headers: server.headers,
            autoFetch: server.autoFetch,
            fetchTimeoutMs: server.fetchTimeoutMs
        };
    }, [
        server?.serverEnabled,
        server?.url,
        server?.headers,
        server?.autoFetch,
        server?.fetchTimeoutMs
    ]);
    const { listPrompts, loading: connectionLoading, error: connectionError } = useMcp(connectionOptions);
    const [prompts, setPrompts] = React.useState([]);
    const [nextCursor, setNextCursor] = React.useState();
    const [isLoadingPrompts, setIsLoadingPrompts] = React.useState(false);
    const [promptsError, setPromptsError] = React.useState(null);
    const fetchPrompts = React.useCallback(async (cursor, append = false) => {
        if (!connectionOptions) {
            setPrompts([]);
            setNextCursor(undefined);
            return;
        }
        setIsLoadingPrompts(true);
        setPromptsError(null);
        try {
            const result = await listPrompts(cursor ? { cursor } : undefined);
            if (result.error) {
                setPromptsError(result.error.message ?? 'Failed to load prompts.');
                setNextCursor(undefined);
                if (!append) {
                    setPrompts([]);
                }
                return;
            }
            setNextCursor(result.nextCursor ?? undefined);
            setPrompts((prev) => (append ? [...prev, ...result.prompts] : result.prompts));
        }
        catch (error) {
            const fallback = error instanceof Error ? error.message : 'Failed to load prompts.';
            setPromptsError(fallback);
            setNextCursor(undefined);
            if (!append) {
                setPrompts([]);
            }
        }
        finally {
            setIsLoadingPrompts(false);
        }
    }, [connectionOptions, listPrompts]);
    React.useEffect(() => {
        if (!connectionOptions) {
            setPrompts([]);
            setNextCursor(undefined);
            return;
        }
        void fetchPrompts(undefined, false);
    }, [connectionOptions, fetchPrompts]);
    const handleRefresh = React.useCallback(() => {
        void fetchPrompts(undefined, false);
    }, [fetchPrompts]);
    const handleLoadMore = React.useCallback(() => {
        if (!nextCursor)
            return;
        void fetchPrompts(nextCursor, true);
    }, [fetchPrompts, nextCursor]);
    const disabledMessage = React.useMemo(() => {
        if (!server) {
            return 'Server configuration not found.';
        }
        if (server.serverEnabled === false) {
            return 'Server is disabled. Enable it in Settings to fetch prompts.';
        }
        if (!server.url) {
            return 'Server URL is missing. Update the server configuration to load prompts.';
        }
        return null;
    }, [server]);
    return (_jsxs("div", { className: theme.mcpToolsView.serverCard, children: [_jsxs("div", { className: 'flex items-start justify-between gap-3', children: [_jsxs("div", { children: [_jsx("h3", { className: 'text-sm font-semibold text-gray-900', children: server?.serverName || 'Unnamed server' }), _jsx("p", { className: 'text-xs text-gray-500', children: server?.url || 'No URL configured' })] }), _jsx("div", { className: 'flex items-center gap-2', children: _jsx("button", { type: 'button', onClick: handleRefresh, disabled: isLoadingPrompts || !connectionOptions, className: 'inline-flex items-center rounded-md border border-gray-200 bg-white px-2 py-1 text-xs font-medium text-gray-600 transition hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-70', children: "Refresh" }) })] }), connectionError && (_jsxs("div", { className: 'mt-3 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700', children: ["Connection error: ", connectionError.message] })), disabledMessage && (_jsx("div", { className: 'mt-3 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-700', children: disabledMessage })), !disabledMessage && (_jsxs("div", { className: 'mt-4 space-y-3', children: [promptsError && (_jsx("div", { className: 'rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700', children: promptsError })), connectionLoading && prompts.length === 0 && !promptsError && (_jsx("div", { className: 'rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-xs text-blue-700', children: "Connecting to server\u2026" })), isLoadingPrompts && prompts.length === 0 && !promptsError && !connectionLoading && (_jsx("div", { className: 'rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-xs text-blue-700', children: "Loading prompts\u2026" })), prompts.length > 0 && (_jsx("ul", { className: 'space-y-3', children: prompts.map((prompt) => (_jsxs("li", { className: 'rounded-lg border border-gray-200 bg-white p-3 shadow-sm', children: [_jsx("div", { className: 'flex items-center justify-between gap-3', children: _jsxs("div", { children: [_jsx("h4", { className: 'text-sm font-semibold text-gray-900', children: prompt.name }), prompt.description && (_jsx("p", { className: 'mt-1 text-xs text-gray-600', children: prompt.description }))] }) }), prompt.arguments && prompt.arguments.length > 0 && (_jsxs("div", { className: 'mt-2', children: [_jsx("h5", { className: 'text-xs font-semibold uppercase tracking-wide text-gray-500', children: "Arguments" }), _jsx("ul", { className: 'mt-1 space-y-1', children: prompt.arguments.map((arg) => (_jsxs("li", { className: 'rounded-md border border-gray-100 bg-gray-50 px-2 py-1 text-xs text-gray-700', children: [_jsx("span", { className: 'font-medium text-gray-900', children: arg.name }), arg.required ? _jsx("span", { className: 'ml-2 rounded-full bg-blue-100 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-blue-700', children: "Required" }) : null, arg.description && _jsx("span", { className: 'ml-2 text-gray-600', children: arg.description })] }, arg.name))) })] }))] }, prompt.name))) })), !promptsError && !isLoadingPrompts && !connectionLoading && prompts.length === 0 && (_jsx("div", { className: 'rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-xs text-gray-600', children: "No prompts returned by this server." })), nextCursor && (_jsx("div", { className: 'pt-2', children: _jsx("button", { type: 'button', onClick: handleLoadMore, disabled: isLoadingPrompts, className: 'inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-3 py-1.5 text-xs font-medium text-blue-700 transition hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-70', children: "Load more" }) })), isLoadingPrompts && prompts.length > 0 && (_jsx("div", { className: 'text-xs text-gray-500', children: "Loading\u2026" }))] }))] }));
};
export default McpPromptsView;
