import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, useCallback, useEffect, useLayoutEffect, useRef } 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);
    // Track whether the input value has been modified by the user.
    // Due to the nature of the input, we must track this through a ref instead of state.
    const modifiedRef = useRef(false);
    useEffect(() => {
        if (inputRef.current && !Number.isNaN(value)) {
            inputRef.current.value = padNumberWithZeros(maxLength, value?.toString());
            modifiedRef.current = false;
        }
    }, [value, maxLength]);
    useLayoutEffect(() => {
        if (inputRef.current) {
            inputRef.current.style.width = `calc(${size}ch + ${size} * ${getComputedStyle(inputRef.current).letterSpacing})`;
        }
    }, [size]);
    useEvent('beforeinput', (event) => {
        if (event.data && !regexPattern.test(event.data)) {
            event.preventDefault();
        }
    }, { target: inputRef });
    const onInputChange = useCallback((e) => {
        const targetEl = e.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`;
        modifiedRef.current = true;
    }, [maxLength, size]);
    const onBlur = useCallback((e) => {
        const targetElValue = e.target.value;
        const paddedValue = padWithZeros
            ? padNumberWithZeros(maxLength, targetElValue)
            : targetElValue;
        e.target.value = paddedValue;
        if (modifiedRef.current) {
            // Only trigger onChange if the value has been modified
            onChange?.(paddedValue);
            modifiedRef.current = false;
        }
    }, [onChange, padWithZeros, maxLength]);
    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