import { jsx as _jsx, jsxs as _jsxs } 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 { useTextBuffer } from '../shared/text-buffer.js';
import { Colors } from '../../colors.js';
import { useKeypress } from '../../hooks/useKeypress.js';
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
const FOCUS_ORDER = ['prompt', 'profile', 'actions'];
export const SubagentEditForm = ({ subagent, profiles: _profiles, pendingProfile, onSave, onCancel, onSelectProfile, isFocused = true, }) => {
    const [focusTarget, setFocusTarget] = useState('prompt');
    const [isEditingPrompt, setIsEditingPrompt] = useState(false);
    const [selectedAction, setSelectedAction] = useState('save');
    const [isSaving, setIsSaving] = useState(false);
    const [error, setError] = useState(null);
    const { rows: terminalRows, columns: terminalColumns } = useTerminalSize();
    const selectedProfile = pendingProfile ?? subagent.profile;
    // Keep conservative to avoid rendering off-screen.
    const NON_EDITOR_HEIGHT = 17;
    const editorHeight = Math.max(4, Math.min(10, terminalRows - NON_EDITOR_HEIGHT));
    const editorWidth = Math.max(20, terminalColumns - 24);
    const promptBuffer = useTextBuffer({
        initialText: subagent.systemPrompt,
        viewport: { width: editorWidth, height: editorHeight },
        isValidPath: () => false,
    });
    const hasChanges = promptBuffer.text !== subagent.systemPrompt ||
        selectedProfile !== subagent.profile;
    const handleSave = useCallback(async () => {
        if (!hasChanges) {
            onCancel();
            return;
        }
        setIsSaving(true);
        setError(null);
        try {
            await onSave(promptBuffer.text, selectedProfile);
        }
        catch (err) {
            setError(err instanceof Error ? err.message : 'Failed to save');
            setIsSaving(false);
        }
    }, [hasChanges, onCancel, onSave, promptBuffer.text, selectedProfile]);
    const visibleLines = promptBuffer.viewportVisualLines;
    const totalVisualLines = promptBuffer.allVisualLines.length;
    const startLine = totalVisualLines > 0 ? promptBuffer.visualScrollRow + 1 : 0;
    const endLine = totalVisualLines > 0
        ? Math.min(startLine + visibleLines.length - 1, totalVisualLines)
        : 0;
    const moveFocus = useCallback((direction) => {
        const currentIndex = FOCUS_ORDER.indexOf(focusTarget);
        const nextIndex = direction === 'up'
            ? Math.max(0, currentIndex - 1)
            : Math.min(FOCUS_ORDER.length - 1, currentIndex + 1);
        setFocusTarget(FOCUS_ORDER[nextIndex]);
    }, [focusTarget]);
    useKeypress((key) => {
        if (isSaving) {
            return;
        }
        if (isEditingPrompt) {
            if (key.name === 'escape') {
                setIsEditingPrompt(false);
                return;
            }
            promptBuffer.handleInput(key);
            return;
        }
        if (key.name === 'escape') {
            onCancel();
            return;
        }
        const isUp = key.name === 'up' || key.sequence === 'k';
        const isDown = key.name === 'down' || key.sequence === 'j';
        const isLeft = key.name === 'left' || key.sequence === 'h';
        const isRight = key.name === 'right' || key.sequence === 'l';
        const isActivate = key.name === 'return' || key.name === 'space';
        if (isUp) {
            moveFocus('up');
            return;
        }
        if (isDown) {
            moveFocus('down');
            return;
        }
        if (focusTarget === 'actions') {
            if (isLeft) {
                setSelectedAction('save');
                return;
            }
            if (isRight) {
                setSelectedAction('cancel');
                return;
            }
        }
        if (!isActivate) {
            return;
        }
        if (focusTarget === 'prompt') {
            setIsEditingPrompt(true);
            return;
        }
        if (focusTarget === 'profile') {
            onSelectProfile();
            return;
        }
        if (focusTarget === 'actions') {
            if (selectedAction === 'save') {
                // eslint-disable-next-line @typescript-eslint/no-floating-promises
                handleSave();
            }
            else {
                onCancel();
            }
        }
    }, { isActive: isFocused && !isSaving });
    const renderLineWithCursor = useCallback((line, idx) => {
        const relativeCursorRow = promptBuffer.visualCursor[0] - promptBuffer.visualScrollRow;
        const isCursorLine = idx === relativeCursorRow;
        if (!isCursorLine || !isEditingPrompt) {
            return (_jsx(Text, { color: Colors.Foreground, wrap: "truncate-end", children: line || ' ' }, idx));
        }
        const col = promptBuffer.visualCursor[1];
        const safeCol = Math.max(0, Math.min(col, line.length));
        const before = line.slice(0, safeCol);
        const at = line[safeCol] ?? ' ';
        const after = line.slice(safeCol + 1);
        return (_jsxs(Text, { color: Colors.Foreground, wrap: "truncate-end", children: [before, _jsx(Text, { color: "#00ff00", children: at }), after] }, idx));
    }, [isEditingPrompt, promptBuffer.visualCursor, promptBuffer.visualScrollRow]);
    const promptHint = useMemo(() => {
        if (isEditingPrompt) {
            return '[ESC] Stop editing (changes kept, not saved)';
        }
        if (focusTarget === 'prompt') {
            return '[Enter] Edit prompt';
        }
        return null;
    }, [focusTarget, isEditingPrompt]);
    const profileHint = useMemo(() => (focusTarget === 'profile' ? ' [Enter] Change Profile' : ''), [focusTarget]);
    const actionsHint = useMemo(() => focusTarget === 'actions' ? '[←/→] Choose  [Enter/Space] Activate' : '', [focusTarget]);
    const saveColor = focusTarget === 'actions' && selectedAction === 'save'
        ? '#00ff00'
        : Colors.Foreground;
    const cancelColor = focusTarget === 'actions' && selectedAction === 'cancel'
        ? '#00ff00'
        : Colors.Foreground;
    return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Box, { marginBottom: 1, children: _jsx(Text, { bold: true, color: Colors.Foreground, children: "Edit Configuration" }) }), _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 }) })), _jsxs(Box, { flexDirection: "column", marginY: 1, children: [_jsxs(Box, { children: [_jsxs(Text, { color: focusTarget === 'prompt' ? '#00ff00' : Colors.Foreground, children: [focusTarget === 'prompt' ? '→ ' : '  ', "1 System Prompt"] }), isEditingPrompt && _jsx(Text, { color: "#00ff00", children: " (editing)" })] }), _jsx(Box, { marginLeft: 4, marginBottom: 1, children: _jsxs(Text, { color: Colors.Gray, children: ["Lines ", startLine, "-", endLine, " of ", totalVisualLines] }) }), _jsx(Box, { marginLeft: 4, flexDirection: "column", borderStyle: "single", borderColor: focusTarget === 'prompt' ? '#00ff00' : Colors.Gray, paddingX: 1, height: editorHeight + 2, overflow: "hidden", children: visibleLines.length > 0 ? (visibleLines.map(renderLineWithCursor)) : (_jsx(Text, { color: Colors.Foreground, children: " " })) }), promptHint && (_jsx(Box, { marginLeft: 4, marginTop: 1, children: _jsx(Text, { color: Colors.Gray, children: promptHint }) }))] }), _jsxs(Box, { flexDirection: "column", marginY: 1, children: [_jsx(Box, { children: _jsxs(Text, { color: focusTarget === 'profile' ? '#00ff00' : Colors.Foreground, children: [focusTarget === 'profile' ? '→ ' : '  ', "2 Profile Assignment"] }) }), _jsxs(Box, { marginLeft: 4, children: [_jsx(Text, { color: Colors.Gray, children: "Current: " }), _jsx(Text, { color: Colors.Foreground, children: selectedProfile }), selectedProfile !== subagent.profile && (_jsx(Text, { color: "#ffff00", children: " (changed)" })), _jsx(Text, { color: Colors.Gray, children: profileHint })] })] }), _jsxs(Box, { flexDirection: "column", marginY: 1, children: [_jsx(Box, { children: _jsxs(Text, { color: focusTarget === 'actions' ? '#00ff00' : Colors.Foreground, children: [focusTarget === 'actions' ? '→ ' : '  ', "3 Actions"] }) }), _jsxs(Box, { marginLeft: 4, children: [_jsx(Text, { color: saveColor, children: "[ Save ]" }), _jsx(Text, { color: Colors.Gray, children: " " }), _jsx(Text, { color: cancelColor, children: "[ Cancel ]" })] }), actionsHint && (_jsx(Box, { marginLeft: 4, children: _jsx(Text, { color: Colors.Gray, children: actionsHint }) }))] }), _jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsx(Text, { color: Colors.Gray, children: "Controls: \u2191\u2193 move focus, Enter activate" }), _jsx(Text, { color: Colors.Gray, children: "ESC closes without saving" }), hasChanges && _jsx(Text, { color: "#ffff00", children: "* Unsaved changes" })] }), isSaving && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { color: Colors.Gray, children: "Saving..." }) }))] }));
};
//# sourceMappingURL=SubagentEditForm.js.map