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 { promises as fs } from 'node:fs';
import path from 'node:path';
import os from 'node:os';
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 { generateProfileNameSuggestions, buildProfileJSON, saveProfile, getStepPosition, } from './utils.js';
export const ProfileSaveStep = ({ state, onUpdateProfileName, onContinue, onBack, onCancel, }) => {
    const [focusedComponent, setFocusedComponent] = useState('input');
    const [saveError, setSaveError] = useState(null);
    const [profileNameInput, setProfileNameInput] = useState(state.profileName || '');
    const [validationError, setValidationError] = useState(null);
    const [existingProfiles, setExistingProfiles] = useState([]);
    // Generate name suggestions on mount
    const [suggestions] = useState(() => generateProfileNameSuggestions(state.config));
    // Handle Escape key to go back
    useKeypress((key) => {
        if (key.name === 'escape') {
            if (focusedComponent === 'input') {
                // Go back to previous step
                onBack();
            }
            else if (focusedComponent === 'conflict') {
                // Go back to input from conflict dialog
                setFocusedComponent('input');
            }
            // Don't allow escape during saving
        }
    }, { isActive: true });
    // Load existing profiles on mount
    useEffect(() => {
        const loadExistingProfiles = async () => {
            try {
                const profilesDir = path.join(os.homedir(), '.llxprt', 'profiles');
                const files = await fs.readdir(profilesDir);
                const profileNames = files
                    .filter((f) => f.endsWith('.json'))
                    .map((f) => f.replace(/\.json$/, ''));
                setExistingProfiles(profileNames);
            }
            catch {
                // Directory might not exist yet
                setExistingProfiles([]);
            }
        };
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        loadExistingProfiles();
    }, []);
    const handleProfileNameChange = useCallback((value) => {
        setProfileNameInput(value);
        if (!value.trim()) {
            setValidationError('Profile name cannot be empty');
            return;
        }
        // Basic validation (async validation happens on submit)
        if (value.includes('/') || value.includes('\\')) {
            setValidationError('Profile name cannot contain path separators');
            return;
        }
        // Check for conflicts (best-effort early validation for UX)
        // Note: Filesystem is the final source of truth via atomic save operation
        if (existingProfiles.includes(value)) {
            setValidationError('Profile name already exists');
            return;
        }
        setValidationError(null);
        onUpdateProfileName(value);
    }, [onUpdateProfileName, existingProfiles]);
    const handleProfileNameSubmit = useCallback(async (forceSave = false) => {
        if (!profileNameInput.trim()) {
            setValidationError('Profile name cannot be empty');
            return;
        }
        if (validationError && !forceSave) {
            // If the only error is "already exists", show conflict dialog
            if (validationError === 'Profile name already exists') {
                setFocusedComponent('conflict');
                return;
            }
            return;
        }
        // Save immediately
        setFocusedComponent('saving');
        setSaveError(null);
        const profileJSON = buildProfileJSON(state);
        // Atomic save operation - filesystem is source of truth for conflicts
        // Uses 'wx' flag by default to prevent overwrite unless forceSave=true
        const result = await saveProfile(profileNameInput, profileJSON, {
            overwrite: forceSave,
        });
        if (result.success) {
            onContinue();
        }
        else if (result.alreadyExists) {
            // Filesystem reports file exists - show conflict dialog
            // This catches stale existingProfiles or race conditions
            setValidationError('Profile name already exists');
            setFocusedComponent('conflict');
        }
        else {
            setSaveError(result.error || 'Failed to save profile');
            setFocusedComponent('input');
        }
    }, [profileNameInput, validationError, state, onContinue]);
    const handleConflictResolution = useCallback((value) => {
        if (value === 'rename') {
            setFocusedComponent('input');
        }
        else if (value === 'overwrite') {
            // Clear validation error and force save
            setValidationError(null);
            // eslint-disable-next-line @typescript-eslint/no-floating-promises
            handleProfileNameSubmit(true);
        }
        else if (value === 'back') {
            onBack();
        }
        else if (value === 'cancel') {
            onCancel();
        }
    }, [onBack, onCancel, handleProfileNameSubmit]);
    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: "Name Your Profile:" }), _jsx(Text, { color: Colors.Gray, children: "Enter a name for this profile" }), _jsx(Text, { color: Colors.Foreground, children: " " }), focusedComponent === 'input' && (_jsxs(_Fragment, { children: [_jsx(Text, { color: Colors.Foreground, children: "Profile name:" }), _jsx(TextInput, { value: profileNameInput, onChange: handleProfileNameChange, onSubmit: handleProfileNameSubmit, isFocused: true, placeholder: "my-profile" }), saveError && _jsxs(Text, { color: Colors.AccentRed, children: ["\u2717 ", saveError] }), validationError && (_jsxs(Text, { color: Colors.AccentRed, children: ["\u2717 ", validationError] })), !validationError && !saveError && profileNameInput && (_jsx(Text, { color: Colors.AccentGreen, children: "\u2713 Name is available" })), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "\u2139 Suggested names:" }), suggestions.map((suggestion) => (_jsxs(Text, { color: Colors.Gray, children: ["\u2022 ", suggestion] }, suggestion))), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(Text, { color: Colors.Gray, children: "\u2190 \u2192 Move cursor Enter Continue Esc Back" })] })), focusedComponent === 'saving' && (_jsx(Text, { color: Colors.Gray, children: "Saving profile..." })), focusedComponent === 'conflict' && (_jsxs(_Fragment, { children: [_jsx(Text, { color: Colors.AccentYellow, children: "Profile Name Conflict" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsxs(Text, { color: Colors.Foreground, children: ["A profile named '", profileNameInput, "' already exists."] }), _jsx(Text, { color: Colors.Gray, children: "Choose a different name or overwrite the existing profile:" }), _jsx(Text, { color: Colors.Foreground, children: " " }), _jsx(RadioButtonSelect, { items: [
                            {
                                label: 'Choose different name',
                                value: 'rename',
                                key: 'rename',
                            },
                            {
                                label: 'Overwrite existing profile',
                                value: 'overwrite',
                                key: 'overwrite',
                            },
                            { label: 'Back', value: 'back', key: 'back' },
                            { label: 'Cancel', value: 'cancel', key: 'cancel' },
                        ], onSelect: handleConflictResolution, isFocused: true })] }))] }));
};
//# sourceMappingURL=ProfileSaveStep.js.map