import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { memo, useState, useCallback, useRef, useEffect } from 'react';
import { Globe, Laptop, Loader2, FolderDot, Terminal } from 'lucide-react';
import { Modal } from '../ui/Modal';
import { Button } from '../ui/Button';
import { Input } from '../ui/Input';
import { useAddMCPServer } from '../../hooks/useMCP';
function parseCommandString(input) {
    const parts = input.trim().split(/\s+/);
    return { command: parts[0] ?? '', args: parts.slice(1) };
}
function parseEnv(envStr) {
    const trimmed = envStr.trim();
    if (!trimmed)
        return undefined;
    const env = {};
    for (const line of trimmed.split('\n')) {
        const eq = line.indexOf('=');
        if (eq > 0) {
            env[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
        }
    }
    return Object.keys(env).length > 0 ? env : undefined;
}
function parseHeaders(headerStr) {
    const trimmed = headerStr.trim();
    if (!trimmed)
        return undefined;
    const headers = {};
    for (const line of trimmed.split('\n')) {
        const colon = line.indexOf(':');
        if (colon > 0) {
            headers[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
        }
    }
    return Object.keys(headers).length > 0 ? headers : undefined;
}
export const AddMCPServerModal = memo(function AddMCPServerModal({ isOpen, onClose, }) {
    const [serverMode, setServerMode] = useState('local');
    const [name, setName] = useState('');
    const [commandStr, setCommandStr] = useState('');
    const [url, setUrl] = useState('');
    const [transport, setTransport] = useState('http');
    const [headersStr, setHeadersStr] = useState('');
    const [envStr, setEnvStr] = useState('');
    const [scope, setScope] = useState('global');
    const [error, setError] = useState(null);
    const addServer = useAddMCPServer();
    const reset = useCallback(() => {
        setName('');
        setCommandStr('');
        setUrl('');
        setTransport('http');
        setHeadersStr('');
        setEnvStr('');
        setScope('global');
        setError(null);
        setServerMode('local');
    }, []);
    const handleClose = useCallback(() => {
        reset();
        onClose();
    }, [reset, onClose]);
    const handleSubmit = useCallback(async () => {
        setError(null);
        const trimmedName = name.trim();
        if (!trimmedName) {
            setError('Server name is required');
            return;
        }
        try {
            if (serverMode === 'local') {
                const trimmedCmd = commandStr.trim();
                if (!trimmedCmd) {
                    setError('Command is required');
                    return;
                }
                if (/^https?:\/\//i.test(trimmedCmd)) {
                    setError('Local commands cannot be URLs. Switch to Remote (HTTP) for remote servers.');
                    return;
                }
                const { command, args } = parseCommandString(trimmedCmd);
                await addServer.mutateAsync({
                    name: trimmedName,
                    transport: 'stdio',
                    command,
                    args,
                    env: parseEnv(envStr),
                    scope,
                });
            }
            else {
                const trimmedUrl = url.trim();
                if (!trimmedUrl) {
                    setError('URL is required');
                    return;
                }
                await addServer.mutateAsync({
                    name: trimmedName,
                    transport,
                    url: trimmedUrl,
                    headers: parseHeaders(headersStr),
                    scope,
                });
            }
            handleClose();
        }
        catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to add server');
        }
    }, [
        name,
        serverMode,
        commandStr,
        envStr,
        url,
        transport,
        headersStr,
        scope,
        addServer,
        handleClose,
    ]);
    const contentRef = useRef(null);
    const [contentHeight, setContentHeight] = useState(undefined);
    useEffect(() => {
        const el = contentRef.current;
        if (!el)
            return;
        const observer = new ResizeObserver(() => {
            setContentHeight(el.scrollHeight);
        });
        observer.observe(el);
        return () => observer.disconnect();
    }, []);
    return (_jsx(Modal, { isOpen: isOpen, onClose: handleClose, title: "Add MCP Server", children: _jsx("div", { className: "overflow-hidden transition-[height] duration-200 ease-in-out", style: { height: contentHeight !== undefined ? contentHeight : 'auto' }, children: _jsxs("div", { ref: contentRef, className: "space-y-4", children: [_jsxs("div", { className: "relative flex w-full rounded-lg bg-muted p-1", children: [_jsx("div", { className: "absolute top-1 bottom-1 rounded-md bg-background shadow-md border border-border transition-all duration-200 ease-in-out", style: {
                                    left: serverMode === 'local' ? '4px' : '50%',
                                    right: serverMode === 'remote' ? '4px' : '50%',
                                } }), _jsxs("button", { type: "button", onClick: () => setServerMode('local'), className: `relative z-10 flex items-center justify-center gap-2 flex-1 text-sm font-medium py-2 rounded-md transition-colors duration-200 ${serverMode === 'local'
                                    ? 'text-foreground'
                                    : 'text-muted-foreground/50'}`, children: [_jsx(Terminal, { className: "w-4 h-4" }), "Local (stdio)"] }), _jsxs("button", { type: "button", onClick: () => setServerMode('remote'), className: `relative z-10 flex items-center justify-center gap-2 flex-1 text-sm font-medium py-2 rounded-md transition-colors duration-200 ${serverMode === 'remote'
                                    ? 'text-foreground'
                                    : 'text-muted-foreground/50'}`, children: [_jsx(Globe, { className: "w-4 h-4" }), "Remote (HTTP)"] })] }), _jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium mb-1", children: "Name" }), _jsx(Input, { value: name, onChange: (e) => setName(e.target.value), placeholder: "e.g. github, linear, helius", autoFocus: true })] }), serverMode === 'local' ? (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium mb-1", children: "Command" }), _jsx(Input, { value: commandStr, onChange: (e) => setCommandStr(e.target.value), placeholder: "e.g. npx -y @modelcontextprotocol/server-github", onKeyDown: (e) => {
                                            if (e.key === 'Enter')
                                                handleSubmit();
                                        } }), _jsxs("p", { className: "text-xs text-muted-foreground mt-1", children: ["Like", ' ', _jsx("code", { className: "bg-muted px-1 rounded", children: "npx -y helius-mcp@latest" })] })] }), _jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium mb-1", children: "Environment Variables" }), _jsx("textarea", { value: envStr, onChange: (e) => setEnvStr(e.target.value), placeholder: 'GITHUB_TOKEN=ghp_xxx\nAPI_KEY=sk-xxx', rows: 2, className: "w-full bg-muted border border-border rounded-md px-3 py-2 text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-primary" }), _jsx("p", { className: "text-xs text-muted-foreground mt-1", children: "One per line: KEY=VALUE" })] })] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium mb-1", children: "URL" }), _jsx(Input, { value: url, onChange: (e) => setUrl(e.target.value), placeholder: "e.g. https://mcp.linear.app/mcp", onKeyDown: (e) => {
                                            if (e.key === 'Enter')
                                                handleSubmit();
                                        } })] }), _jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium mb-1", children: "Transport" }), _jsxs("div", { className: "relative flex w-full rounded-lg border border-border bg-muted/50 p-0.5", children: [_jsx("div", { className: "absolute top-0.5 bottom-0.5 rounded-md bg-background shadow-md border border-border transition-all duration-200 ease-in-out", style: {
                                                    left: transport === 'http' ? '2px' : '50%',
                                                    right: transport === 'sse' ? '2px' : '50%',
                                                } }), _jsx("button", { type: "button", onClick: () => setTransport('http'), className: `relative z-10 flex items-center justify-center gap-1.5 text-xs font-medium py-1.5 rounded-md flex-1 transition-colors duration-200 ${transport === 'http'
                                                    ? 'text-foreground'
                                                    : 'text-muted-foreground/50'}`, children: "HTTP (recommended)" }), _jsx("button", { type: "button", onClick: () => setTransport('sse'), className: `relative z-10 flex items-center justify-center gap-1.5 text-xs font-medium py-1.5 rounded-md flex-1 transition-colors duration-200 ${transport === 'sse'
                                                    ? 'text-foreground'
                                                    : 'text-muted-foreground/50'}`, children: "SSE (legacy)" })] })] }), _jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium mb-1", children: "Headers" }), _jsx("textarea", { value: headersStr, onChange: (e) => setHeadersStr(e.target.value), placeholder: 'Authorization: Bearer xxx', rows: 2, className: "w-full bg-muted border border-border rounded-md px-3 py-2 text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-primary" }), _jsx("p", { className: "text-xs text-muted-foreground mt-1", children: "One per line: Header-Name: value" })] }), _jsx("p", { className: "text-xs text-muted-foreground", children: "For OAuth servers (Linear, Notion, etc.), leave headers empty and authenticate after adding." })] })), _jsxs("div", { children: [_jsx("div", { className: "text-sm font-medium mb-1", children: "Scope" }), _jsxs("div", { className: "relative flex w-full rounded-lg border border-border bg-muted/50 p-0.5", children: [_jsx("div", { className: "absolute top-0.5 bottom-0.5 rounded-md bg-background shadow-md border border-border transition-all duration-200 ease-in-out", style: {
                                            left: scope === 'global' ? '2px' : '50%',
                                            right: scope === 'project' ? '2px' : '50%',
                                        } }), _jsxs("button", { type: "button", onClick: () => setScope('global'), className: `relative z-10 flex items-center justify-center gap-1.5 text-xs font-medium py-1.5 rounded-md flex-1 transition-colors duration-200 ${scope === 'global'
                                            ? 'text-foreground'
                                            : 'text-muted-foreground/50'}`, children: [_jsx(Laptop, { className: "w-3 h-3" }), "All projects"] }), _jsxs("button", { type: "button", onClick: () => setScope('project'), className: `relative z-10 flex items-center justify-center gap-1.5 text-xs font-medium py-1.5 rounded-md flex-1 transition-colors duration-200 ${scope === 'project'
                                            ? 'text-foreground'
                                            : 'text-muted-foreground/50'}`, children: [_jsx(FolderDot, { className: "w-3 h-3" }), "This project only"] })] }), _jsx("p", { className: "text-xs text-muted-foreground mt-1", children: scope === 'global'
                                    ? 'Saved to ~/.config/otto/config.json'
                                    : 'Saved to .otto/config.json (project-local)' })] }), error && (_jsx("div", { className: "text-sm text-red-400 bg-red-500/10 px-3 py-2 rounded", children: error })), _jsxs("div", { className: "flex justify-end gap-2 pt-2", children: [_jsx(Button, { variant: "ghost", onClick: handleClose, children: "Cancel" }), _jsx(Button, { variant: "primary", onClick: handleSubmit, disabled: addServer.isPending, children: addServer.isPending ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "w-3 h-3 animate-spin mr-1" }), "Adding..."] })) : ('Add Server') })] })] }) }) }));
});
//# sourceMappingURL=AddMCPServerModal.js.map