import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import ZodSchemaForm, { lightTheme, darkTheme } from 'zod-schema-form';
import { useTheme, useThemeName } from '../theme';
const inferTransportMode = (values) => {
    if (!values) {
        return 'sse';
    }
    if (values.transportMode === 'stdio') {
        return 'stdio';
    }
    if (values.transportMode === 'sse') {
        return 'sse';
    }
    return values.stdio ? 'stdio' : 'sse';
};
const toInitialValues = (values) => {
    if (!values) {
        return undefined;
    }
    const transportMode = inferTransportMode(values);
    const serverName = values.serverName ?? 'New Server';
    if (transportMode === 'stdio') {
        const stdio = values.stdio;
        const rawArgs = stdio?.args;
        return {
            serverName,
            transportMode,
            command: stdio?.command ?? '',
            args: Array.isArray(rawArgs) ? rawArgs.join(' ') : (typeof rawArgs === 'string' ? rawArgs : ''),
            env: stdio?.env ?? {},
            autoRestart: stdio?.autoRestart ?? true
        };
    }
    return {
        serverName,
        transportMode,
        url: values.url ?? '',
        headers: values.headers ?? {}
    };
};
const sanitizeStdioArgs = (value) => {
    if (!value) {
        return undefined;
    }
    if (Array.isArray(value)) {
        return value.map((entry) => entry.trim()).filter((entry) => entry.length > 0);
    }
    return value
        .split(/\s+/)
        .map((entry) => entry.trim())
        .filter((entry) => entry.length > 0);
};
const sanitizeRecord = (record) => {
    if (!record) {
        return undefined;
    }
    const entries = Object.entries(record)
        .map(([key, value]) => [key.trim(), value.trim()])
        .filter(([key, value]) => key.length > 0 && value.length > 0);
    return entries.length > 0 ? Object.fromEntries(entries) : undefined;
};
const buildSchema = (transportMode) => {
    const base = [
        ['serverName', {
                type: 'string',
                label: 'Server Name',
                required: true,
                default: 'New Server',
                description: 'Display name used throughout the app.'
            }],
        ['transportMode', {
                type: 'string',
                label: 'Transport',
                description: 'Select HTTP(S) streaming for remote servers or STDIO for local processes.',
                enum: ['sse', 'stdio'],
                default: transportMode
            }]
    ];
    if (transportMode === 'stdio') {
        base.push(['command', {
                type: 'string',
                label: 'Command',
                required: true,
                description: 'Executable or script that starts the MCP server.'
            }], ['args', {
                type: 'string',
                label: 'Arguments',
                description: 'Optional space-separated command arguments.'
            }], ['env', {
                type: 'object',
                label: 'Environment variables',
                description: 'Key/value pairs to inject into the spawned process.',
                objectKeyType: 'string',
                objectValueType: 'string'
            }], ['autoRestart', {
                type: 'boolean',
                label: 'Restart on exit',
                description: 'Automatically relaunch if the process exits unexpectedly.',
                default: true
            }]);
        return base;
    }
    base.push(['url', {
            type: 'string',
            label: 'Endpoint URL',
            required: true,
            default: 'https://example.com/mcp',
            description: 'HTTPS endpoint exposed by the MCP server.'
        }], ['headers', {
            type: 'object',
            label: 'Custom headers',
            description: 'Optional HTTP headers to send with every request.',
            objectKeyType: 'string',
            objectValueType: 'string'
        }]);
    return base;
};
const buildStdioConfig = (values) => {
    const command = values?.command?.trim() ?? '';
    const args = sanitizeStdioArgs(values?.args);
    const env = sanitizeRecord(values?.env);
    const config = {
        command,
        autoRestart: values?.autoRestart ?? true
    };
    if (args && args.length > 0) {
        config.args = args;
    }
    if (env && Object.keys(env).length > 0) {
        config.env = env;
    }
    return config;
};
export const NewConnectionForm = ({ initialValues, onSubmit, onCancel }) => {
    const theme = useTheme();
    const themeName = useThemeName();
    const formInitialValues = React.useMemo(() => toInitialValues(initialValues), [initialValues]);
    const [transportMode, setTransportMode] = React.useState(formInitialValues?.transportMode ?? 'sse');
    React.useEffect(() => {
        const nextMode = formInitialValues?.transportMode ?? 'sse';
        setTransportMode((current) => (current === nextMode ? current : nextMode));
    }, [formInitialValues?.transportMode]);
    const schema = React.useMemo(() => buildSchema(transportMode), [transportMode]);
    const handleSubmit = React.useCallback((values) => {
        const resolvedTransport = values.transportMode === 'stdio' || values.transportMode === 'sse'
            ? values.transportMode
            : transportMode;
        const serverName = values.serverName?.trim().length
            ? values.serverName.trim()
            : 'New Server';
        if (resolvedTransport === 'stdio') {
            const command = values?.command?.trim() ?? '';
            if (!command) {
                throw new Error('Command is required for STDIO transport.');
            }
            const stdioConfig = buildStdioConfig(values);
            if (!stdioConfig.command) {
                throw new Error('Command is required for STDIO transport.');
            }
            onSubmit({
                serverName,
                transportMode: 'stdio',
                stdio: stdioConfig
            });
            return;
        }
        const url = values.url?.trim();
        if (!url) {
            throw new Error('Endpoint URL is required for HTTP transport.');
        }
        onSubmit({
            serverName,
            transportMode: 'sse',
            url,
            headers: sanitizeRecord(values.headers)
        });
    }, [onSubmit, transportMode]);
    const handleValueChange = React.useCallback((field, value) => {
        if (field === 'transportMode' && (value === 'sse' || value === 'stdio')) {
            setTransportMode(value);
        }
    }, []);
    return (_jsxs("div", { className: theme.newConnectionForm.container, children: [_jsxs("div", { className: theme.newConnectionForm.header, children: [_jsx("h2", { className: theme.newConnectionForm.title, children: "New Connection" }), _jsx("button", { className: theme.newConnectionForm.backButton, onClick: () => onCancel(initialValues), children: "Back" })] }), _jsx(ZodSchemaForm, { schema: schema, initialValues: formInitialValues, onValueChange: handleValueChange, onSubmit: handleSubmit, submitButtonText: 'Connect', size: 'small', theme: themeName === 'dark' ? darkTheme : lightTheme })] }));
};
