import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import { useState, useCallback } from "react";
import { Box, Text, useInput, useApp } from "ink";
import { c } from "../theme.js";
export function InputComposer({ onSubmit, disabled = false, onCtrlC, }) {
    const [value, setValue] = useState("");
    const { exit } = useApp();
    const handleSubmit = useCallback(() => {
        const trimmed = value.trim();
        if (trimmed.length > 0 && !disabled) {
            onSubmit(trimmed);
            setValue("");
        }
    }, [value, disabled, onSubmit]);
    useInput((input, key) => {
        if (key.ctrl && input === "c") {
            if (onCtrlC) {
                onCtrlC(exit);
            }
            else {
                exit();
            }
            return;
        }
        if (key.ctrl && input === "l") {
            setValue("");
            return;
        }
        if (key.escape) {
            setValue("");
            return;
        }
        if (key.return) {
            handleSubmit();
            return;
        }
        if (!disabled && (key.backspace || key.delete || input === "\x7f")) {
            setValue((v) => v.slice(0, -1));
            return;
        }
        if (!disabled && !key.ctrl && !key.meta && input) {
            setValue((v) => v + input);
        }
    });
    return (_jsxs(Box, { flexDirection: "column", borderStyle: "single", paddingX: 1, children: [_jsxs(Box, { children: [_jsxs(Text, { bold: true, children: [c.dim("Input:"), " "] }), _jsx(Text, { children: value }), _jsx(Text, { children: disabled ? "" : "_" })] }), _jsx(Box, { children: _jsx(Text, { dimColor: true, children: "[Enter send] [Ctrl+C cancel/quit] [Esc clear]" }) })] }));
}
