var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import { jsx as _jsx } from "@emotion/react/jsx-runtime";
import { useEffect, useCallback, useState, useRef, } from 'react';
import isEqual from 'lodash.isequal';
import { useConfig, useCommander } from '../../../../hooks';
import { setValue as setValueCmd } from '../../../../commands';
export const Field = (_a) => {
    var { component, path, onBlur = () => void 0, onChange = () => void 0, onAccept = () => void 0 } = _a, props = __rest(_a, ["component", "path", "onBlur", "onChange", "onAccept"]);
    const initialValue = useConfig(path);
    const { dispatch } = useCommander();
    const valueRef = useRef(initialValue);
    const [value, setValue] = useState(initialValue);
    const InputComponent = component;
    useEffect(() => {
        valueRef.current = initialValue;
        setValue(initialValue);
    }, [initialValue]);
    const handleBlur = useCallback(() => {
        onBlur(valueRef.current);
    }, [onBlur]);
    const handleChange = useCallback((newValue) => {
        valueRef.current = newValue;
        setValue(newValue);
        onChange(newValue);
    }, [onChange]);
    const handleAccept = useCallback(() => {
        if (!isEqual(valueRef.current, initialValue)) {
            dispatch(setValueCmd(path, valueRef.current));
            onAccept(valueRef.current);
        }
    }, [onAccept, path, dispatch, initialValue]);
    return (_jsx(InputComponent, Object.assign({ value: value, onBlur: handleBlur, onChange: handleChange, onAccept: handleAccept }, props)));
};
