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 { PROVIDER_OPTIONS } from './constants.js';
import { validateKeyFile } from './validation.js';
import { getStepPosition } from './utils.js';
export const AuthenticationStep = ({ state, onUpdateAuth, onContinue, onBack, onCancel: _onCancel, }) => {
    const [focusedComponent, setFocusedComponent] = useState('select');
    const [authMethod, setAuthMethod] = useState(null);
    const [authInput, setAuthInput] = useState('');
    const [oauthBuckets, setOauthBuckets] = useState('default');
    const [validationError, setValidationError] = useState(null);
    const [isPathValidated, setIsPathValidated] = useState(false);
    const providerOption = PROVIDER_OPTIONS.find((p) => p.value === state.config.provider);
    // Handle Escape key to go back
    useKeypress((key) => {
        if (key.name === 'escape') {
            if (focusedComponent === 'input') {
                // Go back to auth method selection
                setFocusedComponent('select');
                setValidationError(null);
            }
            else if (focusedComponent === 'select') {
                // Go back to previous step
                onBack();
            }
        }
    }, { isActive: true });
    const handleAuthSelect = useCallback((value) => {
        if (value === 'oauth') {
            setAuthMethod('oauth');
            setFocusedComponent('input'); // Show OAuth bucket input
        }
        else if (value === 'skip') {
            setAuthMethod('skip');
            onUpdateAuth({ type: null });
            onContinue();
        }
        else if (value === 'apikey') {
            setAuthMethod('apikey');
            setFocusedComponent('input');
        }
        else if (value === 'keyfile') {
            setAuthMethod('keyfile');
            setFocusedComponent('input');
        }
        else if (value === '__back__') {
            onBack();
        }
    }, [onUpdateAuth, onContinue, onBack]);
    const handleAuthInputChange = useCallback((value) => {
        setAuthInput(value);
        setValidationError(null);
        setIsPathValidated(false);
    }, []);
    const handleAuthInputSubmit = useCallback(async () => {
        // OAuth bucket input
        if (authMethod === 'oauth') {
            const buckets = oauthBuckets
                .split(',')
                .map((b) => b.trim())
                .filter((b) => b.length > 0);
            onUpdateAuth({
                type: 'oauth',
                buckets: buckets.length > 0 ? buckets : ['default'],
            });
            onContinue();
            return;
        }
        // API key or keyfile
        if (!authInput.trim()) {
            setValidationError('This field cannot be empty');
            return;
        }
        // Validate keyfile path if keyfile method
        if (authMethod === 'keyfile') {
            const validation = await validateKeyFile(authInput);
            if (!validation.valid) {
                setValidationError(validation.error || 'Invalid file path');
                return;
            }
            setIsPathValidated(true);
        }
        setValidationError(null);
        // Store auth value and proceed
        if (authMethod === 'apikey') {
            onUpdateAuth({ type: 'apikey', value: authInput });
        }
        else if (authMethod === 'keyfile') {
            onUpdateAuth({ type: 'keyfile', value: authInput });
        }
        // Proceed to next step
        onContinue();
    }, [authInput, authMethod, oauthBuckets, onUpdateAuth, onContinue]);
    // Build auth options based on provider
    const authOptions = [];
    // API key option
    authOptions.push({
        label: 'Enter API key now',
        value: 'apikey',
        key: 'apikey',
    });
    // Key file option
    authOptions.push({
        label: 'Use key file (provide path)',
        value: 'keyfile',
        key: 'keyfile',
    });
    // OAuth option (only if supported)
    if (providerOption?.supportsOAuth) {
        authOptions.push({
            label: 'OAuth (authenticate when needed)',
            value: 'oauth',
            key: 'oauth',
        });
    }
    // Always allow skipping auth (can be configured later)
    authOptions.push({
        label: 'Skip for now (configure manually later)',
        value: 'skip',
        key: 'skip',
    });
    // Back option
    authOptions.push({
        label: '← Back',
        value: '__back__',
        key: '__back__',
    });
    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: focusedComponent === 'input'
                    ? authMethod === 'apikey'
                        ? 'Enter API Key:'
                        : authMethod === 'keyfile'
                            ? 'Specify Key File:'
                            : 'Configure OAuth:'
                    : 'Authentication:' }), _jsx(Text, { color: Colors.Gray, children: focusedComponent === 'input'
                    ? authMethod === 'apikey'
                        ? `Enter your ${providerOption?.label || state.config.provider} API key:`
                        : authMethod === 'keyfile'
                            ? 'Enter the path to your API key file:'
                            : 'OAuth authentication will be set up when you load this profile'
                    : `Choose how to authenticate with ${providerOption?.label || state.config.provider}` }), _jsx(Text, { color: Colors.Foreground, children: " " }), focusedComponent === 'select' && (_jsxs(_Fragment, { children: [_jsx(RadioButtonSelect, { items: authOptions, onSelect: handleAuthSelect, isFocused: true }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "Esc Back" })] })), focusedComponent === 'input' && authMethod === 'apikey' && (_jsxs(_Fragment, { children: [_jsx(Text, { color: Colors.Foreground, children: "API Key:" }), _jsx(TextInput, { value: authInput, onChange: handleAuthInputChange, onSubmit: handleAuthInputSubmit, isFocused: true, mask: true, placeholder: "sk-..." }), validationError && (_jsxs(Text, { color: Colors.AccentRed, children: ["\u2717 ", validationError] })), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "\u2139 Your key will be stored in the profile JSON file." }), _jsx(Text, { color: Colors.Gray, children: "For better security, consider using a key file instead." }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "Enter Continue Esc Back to list" })] })), focusedComponent === 'input' && authMethod === 'keyfile' && (_jsxs(_Fragment, { children: [_jsx(Text, { color: Colors.Foreground, children: "Key file path:" }), _jsx(TextInput, { value: authInput, onChange: handleAuthInputChange, onSubmit: handleAuthInputSubmit, isFocused: true, placeholder: "~/.keys/provider.key" }), validationError && (_jsxs(Text, { color: Colors.AccentRed, children: ["\u2717 ", validationError] })), !validationError && isPathValidated && (_jsx(Text, { color: Colors.AccentGreen, children: "\u2713 Valid path" })), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "\u2139 Supports ~ expansion for home directory" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "\u2190 \u2192 Move cursor Enter Continue Esc Back to list" })] })), focusedComponent === 'input' && authMethod === 'oauth' && (_jsxs(_Fragment, { children: [_jsx(Text, { color: Colors.Foreground, children: "OAuth Buckets (optional):" }), _jsx(Text, { color: Colors.Gray, children: "Enter comma-separated bucket names, or leave empty for default" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(TextInput, { value: oauthBuckets, onChange: setOauthBuckets, onSubmit: handleAuthInputSubmit, isFocused: true, placeholder: "default, work" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "\u2139 You'll authenticate when you first load this profile" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "Enter Continue Esc Back to list" })] }))] }));
};
//# sourceMappingURL=AuthenticationStep.js.map