import { jsx as _jsx, jsxs as _jsxs } from "@emotion/react/jsx-runtime";
import { useCallback, useState, useEffect, useRef, } from 'react';
import { useTranslation } from 'react-i18next';
import { Space, Input, Button } from 'antd';
import { CloseOutlined, EditOutlined } from '@ant-design/icons';
import { Labelled } from '../../../components/labelled';
import { KeyPickerSpaceCompactCSS, KeyPickerButtonCSS, } from './keyboard-control.style';
const ENTER_KEY_CODE = 'Enter';
const SPACE_KEY_CODE = 'Space';
export const KeyPicker = ({ value, onChange, }) => {
    const { t } = useTranslation();
    const [editMode, setEditMode] = useState(false);
    const [valueVisible, setValueVisible] = useState(true);
    const inputRef = useRef(null);
    useEffect(() => {
        setValueVisible(true);
    }, [value]);
    const handleKeyChange = useCallback((event) => {
        if (editMode) {
            event.preventDefault();
            if (event.code !== value) {
                onChange(event.code);
            }
            else {
                setValueVisible(true);
            }
            setEditMode(false);
            return;
        }
        if (event.code === ENTER_KEY_CODE || event.code === SPACE_KEY_CODE) {
            setEditMode(true);
            setValueVisible(false);
        }
    }, [editMode, value]);
    const handleBlur = useCallback(() => {
        setEditMode(false);
        setValueVisible(true);
    }, []);
    const handleClick = useCallback(() => {
        var _a;
        if (!editMode) {
            (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
        }
        setEditMode(!editMode);
        setValueVisible(!valueVisible);
    }, [editMode, valueVisible]);
    return (_jsx(Labelled, { label: t('components.keyboardControl.bind.key.title'), children: _jsxs(Space.Compact, { css: KeyPickerSpaceCompactCSS, size: "small", children: [_jsx(Input, { ref: inputRef, onKeyDown: handleKeyChange, onBlur: handleBlur, value: valueVisible ? value : '', readOnly: !editMode }), _jsx(Button, { css: KeyPickerButtonCSS, icon: !editMode ? _jsx(EditOutlined, {}) : _jsx(CloseOutlined, {}), onClick: handleClick })] }) }));
};
