import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { useState, useCallback } from 'react';
import { Box, Text } from 'ink';
import { Colors } from '../../colors.js';
import { RadioButtonSelect } from '../shared/RadioButtonSelect.js';
import { TextInput } from './TextInput.js';
import { useKeypress } from '../../hooks/useKeypress.js';
import { PARAMETER_DEFAULTS } from './constants.js';
import { PARAM_VALIDATORS } from './validation.js';
import { getStepPosition } from './utils.js';
export const AdvancedParamsStep = ({ state, onUpdateParams, onContinue, onBack: _onBack, onCancel, }) => {
    const [focusedComponent, setFocusedComponent] = useState('select');
    const [customParams, setCustomParams] = useState({
        temperature: undefined,
        maxTokens: undefined,
        contextLimit: undefined,
    });
    const [currentField, setCurrentField] = useState('temperature');
    const [fieldInput, setFieldInput] = useState('');
    const [validationError, setValidationError] = useState(null);
    // Handle Escape key to cancel or go back
    useKeypress((key) => {
        if (key.name === 'escape') {
            if (focusedComponent === 'custom') {
                // Go back to selection menu
                setFocusedComponent('select');
                setFieldInput('');
                setValidationError(null);
            }
            else {
                // Cancel wizard
                onCancel();
            }
        }
    }, { isActive: true });
    const handleParamSelect = useCallback((value) => {
        if (value === 'defaults') {
            // Use provider defaults
            const defaults = PARAMETER_DEFAULTS[state.config.provider || ''] ||
                PARAMETER_DEFAULTS.anthropic;
            onUpdateParams(defaults);
            onContinue();
        }
        else if (value === 'skip') {
            // Skip params (use system defaults)
            onUpdateParams(undefined);
            onContinue();
        }
        else if (value === 'custom') {
            // Enter custom configuration mode
            setFocusedComponent('custom');
            setCurrentField('temperature');
        }
    }, [state.config.provider, onUpdateParams, onContinue]);
    const handleFieldChange = useCallback((value) => {
        setFieldInput(value);
        setValidationError(null);
    }, []);
    const handleFieldSubmit = useCallback(() => {
        const numValue = currentField === 'temperature'
            ? Number.parseFloat(fieldInput)
            : Number.parseInt(fieldInput, 10);
        if (!fieldInput.trim()) {
            // Allow skipping individual fields
            setFieldInput('');
            setValidationError(null);
            // Move to next field
            if (currentField === 'temperature') {
                setCurrentField('maxTokens');
            }
            else if (currentField === 'maxTokens') {
                setCurrentField('contextLimit');
            }
            else {
                // Done with all fields
                onUpdateParams(customParams);
                onContinue();
            }
            return;
        }
        if (Number.isNaN(numValue)) {
            setValidationError('Must be a valid number');
            return;
        }
        // Validate the field
        const validation = PARAM_VALIDATORS[currentField](numValue);
        if (!validation.valid) {
            setValidationError(validation.error || 'Invalid value');
            return;
        }
        // Update custom params
        const updated = { ...customParams, [currentField]: numValue };
        setCustomParams(updated);
        setFieldInput('');
        setValidationError(null);
        // Move to next field or complete
        if (currentField === 'temperature') {
            setCurrentField('maxTokens');
        }
        else if (currentField === 'maxTokens') {
            setCurrentField('contextLimit');
        }
        else {
            // Done with all fields
            onUpdateParams(updated);
            onContinue();
        }
    }, [fieldInput, currentField, customParams, onUpdateParams, onContinue]);
    const providerDefaults = PARAMETER_DEFAULTS[state.config.provider || ''] ||
        PARAMETER_DEFAULTS.anthropic;
    const paramOptions = [
        {
            label: `Use recommended defaults (temp: ${providerDefaults.temperature}, max tokens: ${providerDefaults.maxTokens})`,
            value: 'defaults',
            key: 'defaults',
        },
        {
            label: 'Configure custom parameters',
            value: 'custom',
            key: 'custom',
        },
        {
            label: 'Skip (use system defaults)',
            value: 'skip',
            key: 'skip',
        },
    ];
    const fieldLabels = {
        temperature: 'Temperature (0.0-2.0)',
        maxTokens: 'Max Tokens (positive integer)',
        contextLimit: 'Context Limit (positive integer)',
    };
    const fieldHelp = {
        temperature: 'Controls randomness. Lower = more focused, Higher = more creative',
        maxTokens: 'Maximum tokens to generate in responses',
        contextLimit: 'Maximum context window size',
    };
    const { current, total } = getStepPosition(state);
    return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { bold: true, color: Colors.AccentCyan, children: ["Create New Profile - Step ", current, " of ", total] }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Foreground, children: "Advanced Parameters:" }), _jsx(Text, { color: Colors.Gray, children: "Configure temperature, max tokens, and context limits (optional)" }), _jsx(Text, { color: Colors.Foreground, children: " " }), focusedComponent === 'select' && (_jsxs(_Fragment, { children: [_jsx(RadioButtonSelect, { items: paramOptions, onSelect: handleParamSelect, isFocused: true }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "Esc Cancel" })] })), focusedComponent === 'custom' && (_jsxs(_Fragment, { children: [_jsxs(Text, { color: Colors.Foreground, children: [fieldLabels[currentField], ":"] }), _jsx(Text, { color: Colors.Gray, children: fieldHelp[currentField] }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(TextInput, { value: fieldInput, onChange: handleFieldChange, onSubmit: handleFieldSubmit, isFocused: true, placeholder: currentField === 'temperature' ? '1.0' : '4096' }), validationError && (_jsxs(Text, { color: Colors.AccentRed, children: ["\u2717 ", validationError] })), !validationError && fieldInput && (_jsx(Text, { color: Colors.AccentGreen, children: "\u2713 Valid" })), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "Press Enter to set value or leave empty to skip" }), _jsxs(Text, { color: Colors.Gray, children: ["Progress:", ' ', currentField === 'temperature'
                                ? '1'
                                : currentField === 'maxTokens'
                                    ? '2'
                                    : '3', "/3"] }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "Enter Continue Esc Back to menu" })] }))] }));
};
//# sourceMappingURL=AdvancedParamsStep.js.map