import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, useCallback, useEffect } from 'react';
import { useConsolidatedRef, useEvent } from '../../../hooks';
import { BareInput } from './DateTime.styles';
const regexPattern = /[0-9]/;
const padNumberWithZeros = (maxLength, value = '') => {
    if (value === '')
        return '';
    return value.padStart(Number.isFinite(maxLength) ? maxLength : 0, '0');
};
const PartInput = forwardRef(function PartInput({ value, onChange, readOnly, min = 0, max = Infinity, size = 2, maxLength = Infinity, padWithZeros = true, ...restProps }, ref) {
    const inputRef = useConsolidatedRef(ref);
    useEffect(() => {
        if (inputRef.current && !Number.isNaN(value)) {
            inputRef.current.value = padNumberWithZeros(maxLength, value?.toString());
        }
    }, [value, inputRef.current]);
    useEvent('beforeinput', (event) => {
        if (event.data && !regexPattern.test(event.data)) {
            event.preventDefault();
        }
    }, { target: inputRef });
    const onInputChange = useCallback((ev) => {
        const targetEl = ev.target;
        if (targetEl.value.length > maxLength)
            targetEl.value = targetEl.value.slice(0, maxLength);
        else if (size !== maxLength)
            targetEl.style.width = `${Math.max(targetEl.value.length, size)}ch`;
    }, [maxLength]);
    const onBlur = useCallback((ev) => {
        const targetElValue = ev.target.value;
        const paddedValue = padWithZeros
            ? padNumberWithZeros(maxLength, targetElValue)
            : targetElValue;
        ev.target.value = paddedValue;
        onChange?.(paddedValue);
    }, [onChange]);
    const defaultValue = value !== undefined ? padNumberWithZeros(maxLength, value?.toString()) : '';
    return (_jsx(BareInput, { type: 'number', defaultValue: defaultValue, onBlur: onBlur, onChange: onInputChange, step: 1, min: min, max: max, maxLength: maxLength, readOnly: readOnly, ref: inputRef, size: size, ...restProps }));
});
export default PartInput;
//# sourceMappingURL=PartInput.js.map