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, useEffect } 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 { PROVIDER_OPTIONS } from './constants.js';
import { getStepPosition } from './utils.js';
import { useRuntimeApi } from '../../contexts/RuntimeContext.js';
export const ModelSelectStep = ({ state, onUpdateModel, onContinue, onBack, onCancel: _onCancel, }) => {
    const [focusedComponent, setFocusedComponent] = useState('select');
    const [customModelInput, setCustomModelInput] = useState('');
    // Handle Escape key to go back
    useKeypress((key) => {
        if (key.name === 'escape') {
            if (focusedComponent === 'input') {
                // Go back to select from custom input
                setFocusedComponent('select');
            }
            else {
                // Go back to previous step
                onBack();
            }
        }
    }, { isActive: true });
    const handleModelSelect = useCallback((value) => {
        if (value === '__custom__') {
            // User selected "Enter custom model name"
            setFocusedComponent('input');
        }
        else if (value === '__back__') {
            // User selected "Back"
            onBack();
        }
        else {
            onUpdateModel(value);
            // Automatically proceed to next step
            onContinue();
        }
    }, [onUpdateModel, onContinue, onBack]);
    const handleCustomModelSubmit = useCallback(() => {
        if (customModelInput.trim()) {
            onUpdateModel(customModelInput.trim());
            // Automatically proceed to next step
            onContinue();
        }
    }, [customModelInput, onUpdateModel, onContinue]);
    // Fetch models from provider via runtime API (hydrated with models.dev data)
    const runtime = useRuntimeApi();
    const [models, setModels] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    useEffect(() => {
        const loadModels = async () => {
            if (!state.config.provider) {
                setIsLoading(false);
                return;
            }
            setIsLoading(true);
            try {
                const hydratedModels = await runtime.listAvailableModels(state.config.provider);
                // Filter out deprecated models and extract IDs
                const modelIds = hydratedModels
                    .filter((m) => m.metadata?.status !== 'deprecated')
                    .map((m) => m.id);
                setModels(modelIds);
            }
            catch {
                // If fetching fails, allow manual entry
                setModels([]);
            }
            setIsLoading(false);
        };
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        loadModels();
    }, [runtime, state.config.provider]);
    const hasKnownModels = models.length > 0;
    // Still need providerOption for label display
    const providerOption = PROVIDER_OPTIONS.find((p) => p.value === state.config.provider);
    // Build model list with "custom" option if provider has known models
    const modelItems = hasKnownModels
        ? [
            ...models.map((m, idx) => ({
                label: idx === 0 ? `${m} (Recommended)` : m,
                value: m,
                key: m,
            })),
            {
                label: 'Enter custom model name...',
                value: '__custom__',
                key: '__custom__',
            },
            {
                label: '← Back',
                value: '__back__',
                key: '__back__',
            },
        ]
        : [];
    const selectedModel = state.config.model || undefined;
    const initialIndex = selectedModel && hasKnownModels
        ? models.findIndex((m) => m === selectedModel)
        : undefined;
    const { current, total } = getStepPosition(state);
    // Show loading state while fetching models
    if (isLoading) {
        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.Gray, children: "Loading models..." })] }));
    }
    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: focusedComponent === 'input' ? 'Enter Model Name:' : 'Select Model:' }), _jsx(Text, { color: Colors.Gray, children: focusedComponent === 'input'
                    ? "Enter the model name exactly as it appears in your provider's documentation"
                    : `Choose the AI model for ${providerOption?.label || state.config.provider}` }), _jsx(Text, { color: Colors.Foreground, children: " " }), focusedComponent === 'select' && hasKnownModels && (_jsxs(_Fragment, { children: [_jsx(RadioButtonSelect, { items: modelItems, initialIndex: initialIndex, onSelect: handleModelSelect, isFocused: true }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "Esc Back" })] })), focusedComponent === 'select' && !hasKnownModels && (_jsxs(_Fragment, { children: [_jsx(Text, { color: Colors.Gray, children: "This provider doesn't have a predefined model list." }), _jsx(Text, { color: Colors.Gray, children: "Enter the model name manually:" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Foreground, children: "Model name:" }), _jsx(TextInput, { value: customModelInput, onChange: setCustomModelInput, onSubmit: handleCustomModelSubmit, isFocused: true, placeholder: "model-name" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "\u2190 \u2192 Move cursor Enter Continue Esc Back" })] })), focusedComponent === 'input' && (_jsxs(_Fragment, { children: [_jsx(Text, { color: Colors.Foreground, children: "Model name:" }), _jsx(TextInput, { value: customModelInput, onChange: setCustomModelInput, onSubmit: handleCustomModelSubmit, isFocused: true, placeholder: "model-name" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "For Ollama: Run 'ollama list' to see available models" }), _jsx(Text, { color: Colors.Gray, children: "For custom providers: Check provider documentation" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "\u2190 \u2192 Move cursor Enter Continue Esc Back to list" })] }))] }));
};
//# sourceMappingURL=ModelSelectStep.js.map