import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { useState, useCallback, useMemo } from 'react';
import { Box, Text } from 'ink';
import { Colors } from '../../colors.js';
import { useKeypress } from '../../hooks/useKeypress.js';
import { RadioButtonSelect } from '../shared/RadioButtonSelect.js';
import { CreateStep } from './types.js';
export const SubagentCreationWizard = ({ profiles, activeProfileName, onSave, onCancel, isFocused = true, }) => {
    const [state, setState] = useState({
        currentStep: CreateStep.FORM,
        name: '',
        mode: 'auto',
        systemPrompt: '',
        selectedProfile: (activeProfileName && profiles.includes(activeProfileName)
            ? activeProfileName
            : profiles[0]) || '',
        validationErrors: {},
    });
    const [focusedField, setFocusedField] = useState('name');
    const [isEditing, setIsEditing] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [error, setError] = useState(null);
    const [showModeSelect, setShowModeSelect] = useState(false);
    const [showProfileSelect, setShowProfileSelect] = useState(false);
    const fields = useMemo(() => ['name', 'mode', 'systemPrompt', 'profile'], []);
    const validateName = useCallback((name) => {
        if (!name.trim())
            return 'Name is required';
        if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
            return 'Only letters, numbers, hyphens, and underscores allowed';
        }
        return null;
    }, []);
    const handleInput = useCallback((char) => {
        setState((prev) => {
            if (focusedField === 'profile' || focusedField === 'mode')
                return prev;
            if (focusedField === 'name' && char === ' ')
                return prev;
            const field = focusedField;
            if (char === '\n' && field === 'systemPrompt') {
                return { ...prev, [field]: prev[field] + '\n' };
            }
            return { ...prev, [field]: prev[field] + char };
        });
    }, [focusedField]);
    const handleBackspace = useCallback(() => {
        setState((prev) => {
            if (focusedField === 'profile' || focusedField === 'mode')
                return prev;
            const field = focusedField;
            return { ...prev, [field]: prev[field].slice(0, -1) };
        });
    }, [focusedField]);
    const handleSave = useCallback(async () => {
        const nameError = validateName(state.name);
        if (nameError) {
            setError(nameError);
            return;
        }
        if (!state.systemPrompt.trim()) {
            setError(state.mode === 'auto'
                ? 'Description is required'
                : 'System prompt is required');
            return;
        }
        if (!state.selectedProfile) {
            setError('Profile is required');
            return;
        }
        setIsSaving(true);
        setError(null);
        try {
            await onSave(state.name, state.systemPrompt, state.selectedProfile, state.mode);
            setIsSaving(false);
        }
        catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to create');
            setIsSaving(false);
        }
    }, [state, validateName, onSave]);
    const handleModeSelect = useCallback((mode) => {
        setState((prev) => ({ ...prev, mode }));
        setShowModeSelect(false);
        setFocusedField('mode');
    }, []);
    const handleProfileSelect = useCallback((profile) => {
        setState((prev) => ({ ...prev, selectedProfile: profile }));
        setShowProfileSelect(false);
        setFocusedField('profile');
    }, []);
    const moveField = useCallback((delta) => {
        const currentIndex = fields.indexOf(focusedField);
        let newIndex = currentIndex + delta;
        if (newIndex < 0)
            newIndex = 0;
        if (newIndex >= fields.length)
            newIndex = fields.length - 1;
        setFocusedField(fields[newIndex]);
    }, [focusedField, fields]);
    useKeypress((key) => {
        const input = key.sequence;
        if (isSaving)
            return;
        // Mode selection mode
        if (showModeSelect) {
            if (key.name === 'escape') {
                setShowModeSelect(false);
            }
            return;
        }
        // Profile selection mode
        if (showProfileSelect) {
            if (key.name === 'escape') {
                setShowProfileSelect(false);
            }
            return;
        }
        // Editing mode
        if (isEditing) {
            if (key.name === 'escape') {
                setIsEditing(false);
                return;
            }
            if (key.name === 'backspace' || key.name === 'delete') {
                handleBackspace();
                return;
            }
            if (key.name === 'return' && focusedField === 'systemPrompt') {
                handleInput('\n');
                return;
            }
            if (key.name === 'return' && focusedField === 'name') {
                setIsEditing(false);
                moveField(1);
                return;
            }
            if (input && !key.ctrl && !key.meta) {
                handleInput(input);
            }
            return;
        }
        // Navigation mode
        if (key.name === 'escape') {
            onCancel();
            return;
        }
        if (key.name === 'up') {
            moveField(-1);
            return;
        }
        if (key.name === 'down') {
            moveField(1);
            return;
        }
        if (key.name === 'return') {
            if (focusedField === 'mode') {
                setShowModeSelect(true);
            }
            else if (focusedField === 'profile') {
                setShowProfileSelect(true);
            }
            else {
                setIsEditing(true);
            }
            return;
        }
        // Quick save with 's'
        if (input === 's') {
            // eslint-disable-next-line @typescript-eslint/no-floating-promises
            handleSave();
            return;
        }
    }, { isActive: isFocused && !isSaving });
    // Mode selection modal
    if (showModeSelect) {
        const modeItems = [
            {
                label: 'Manual (enter full system prompt)',
                value: 'manual',
                key: 'manual',
            },
            {
                label: 'Auto (LLM expands your description)',
                value: 'auto',
                key: 'auto',
            },
        ];
        return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: Colors.Foreground, children: "Select Mode" }), _jsx(Text, { color: Colors.Gray, children: "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500" }), _jsx(RadioButtonSelect, { items: modeItems, onSelect: handleModeSelect, isFocused: true, initialIndex: state.mode === 'auto' ? 1 : 0, maxItemsToShow: 10 }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: Colors.Gray, children: "[ESC] Cancel" }) })] }));
    }
    // Profile selection modal
    if (showProfileSelect) {
        const profileItems = profiles.map((p) => ({
            label: p,
            value: p,
            key: p,
        }));
        return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: Colors.Foreground, children: "Select Profile" }), _jsx(Text, { color: Colors.Gray, children: "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500" }), _jsx(RadioButtonSelect, { items: profileItems, onSelect: handleProfileSelect, isFocused: true, maxItemsToShow: 10 }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: Colors.Gray, children: "[ESC] Cancel" }) })] }));
    }
    const renderField = (field, label, step, value, multiline = false) => {
        const isFieldFocused = focusedField === field;
        const isCurrentlyEditing = isFieldFocused && isEditing;
        const isSelectionField = field === 'profile' || field === 'mode';
        return (_jsxs(Box, { flexDirection: "column", marginY: 1, children: [_jsx(Box, { children: _jsxs(Text, { color: isFieldFocused ? '#00ff00' : Colors.Foreground, children: [isFieldFocused ? '→ ' : '  ', step, " ", label] }) }), isSelectionField ? (_jsxs(Box, { marginLeft: 4, children: [_jsx(Text, { color: Colors.Gray, children: "Current: " }), _jsx(Text, { color: Colors.Foreground, children: value || '(none)' }), isFieldFocused && _jsx(Text, { color: Colors.Gray, children: " [Enter] Select" })] })) : isCurrentlyEditing ? (_jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "#00ff00", marginLeft: 4, paddingX: 1, children: [multiline ? (_jsxs(_Fragment, { children: [value.split('\n').map((line, idx) => (_jsx(Text, { color: Colors.Foreground, children: line || ' ' }, idx))), _jsx(Text, { color: "#00ff00", children: "|" })] })) : (_jsxs(Text, { color: Colors.Foreground, children: [value, _jsx(Text, { color: "#00ff00", children: "|" })] })), _jsx(Text, { color: Colors.Gray, children: multiline ? '[ESC] Done Editing' : '[Enter] Next field' })] })) : (_jsxs(Box, { marginLeft: 4, children: [_jsx(Text, { color: Colors.Gray, children: value
                                ? multiline
                                    ? value.length > 40
                                        ? `[${value.slice(0, 40)}...]`
                                        : value
                                    : value
                                : '(empty)' }), isFieldFocused && _jsx(Text, { color: Colors.Gray, children: " [Enter] Edit" })] }))] }, field));
    };
    return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: Colors.Foreground, children: "Create New Subagent" }), _jsx(Text, { color: Colors.Gray, children: "\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500" }), error && (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: "#ff0000", children: error }) })), _jsx(Box, { marginTop: 1, children: _jsx(Text, { bold: true, color: Colors.Foreground, children: "Step 1: Name" }) }), renderField('name', 'Name (a-z, 0-9, -, _)', 1, state.name), _jsx(Box, { marginTop: 1, children: _jsx(Text, { bold: true, color: Colors.Foreground, children: "Step 2: Mode" }) }), renderField('mode', 'Mode', 2, state.mode), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { bold: true, color: Colors.Foreground, children: ["Step 3: ", state.mode === 'auto' ? 'Description' : 'System Prompt'] }) }), renderField('systemPrompt', state.mode === 'auto' ? 'Description' : 'System Prompt', 3, state.systemPrompt, true), _jsx(Box, { marginTop: 1, children: _jsx(Text, { bold: true, color: Colors.Foreground, children: "Step 4: Profile Assignment" }) }), renderField('profile', 'Profile', 4, state.selectedProfile), _jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsx(Text, { color: Colors.Gray, children: "Controls: \u2191\u2193 Navigate fields [Enter] Edit/Select" }), _jsx(Text, { color: Colors.Gray, children: " [s] Save [ESC] Cancel" }), _jsxs(Text, { color: Colors.Gray, children: [' ', "Current field: ", focusedField, isEditing ? ' (editing)' : ''] })] }), isSaving && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { color: Colors.Gray, children: "Creating subagent..." }) }))] }));
};
//# sourceMappingURL=SubagentCreationWizard.js.map