import React, { forwardRef, useRef, useState } from "react";
import { NumericFormat, numericFormatter } from "react-number-format";
import { useForkRef } from "../../hooks";
export const composeNumberFormat = (InputComponent)=>{
    return /*#__PURE__*/ forwardRef(({ thousandSeparator = ' ', decimalScale = 3, decimalSeparator = '.', disabled, value: outerValue, onChange, defaultValue, onPaste, ...rest }, outerRef)=>{
        const inputRef = useRef(null);
        const inputForkRef = useForkRef(inputRef, outerRef);
        const [innerValue, setInnerValue] = useState(defaultValue || '');
        const value = numericFormatter(String(outerValue ?? innerValue), {
            thousandSeparator,
            decimalScale,
            decimalSeparator
        });
        const handleChangeValue = (values, sourceInfo)=>{
            const changeEvent = sourceInfo.event;
            setInnerValue(values.value);
            if (onChange) {
                onChange(changeEvent, values);
            }
        };
        const handlePaste = (event)=>{
            if (disabled) {
                return;
            }
            if (decimalSeparator !== '.' && inputRef.current) {
                if (!Number.isNaN(Number(event.clipboardData.getData('text/plain')))) {
                    event.preventDefault();
                    const pastedValue = event.clipboardData.getData('text/plain').replace('.', decimalSeparator);
                    const input = event.target;
                    const startPos = input.selectionStart || 0;
                    const newCursorPos = startPos + pastedValue.length;
                    setInnerValue(pastedValue);
                    setTimeout(()=>{
                        inputRef.current?.setSelectionRange(newCursorPos, newCursorPos);
                    }, 10);
                }
            }
            if (onPaste) {
                onPaste(event);
            }
        };
        return /*#__PURE__*/ React.createElement(NumericFormat, {
            value: value,
            disabled: disabled,
            thousandSeparator: thousandSeparator,
            decimalScale: decimalScale,
            decimalSeparator: decimalSeparator,
            customInput: InputComponent,
            getInputRef: inputForkRef,
            _textEllipsisDisable: true,
            onValueChange: handleChangeValue,
            onPaste: handlePaste,
            ...rest
        });
    });
};
