import {NumberInput, NumberInputProps} from "@mantine/core";
import {useEffect, useState} from "react";
import {useDebouncedValue} from "@mantine/hooks";
import {isNumber, omit} from "lodash";


type Props = NumberInputProps;

const DebouncedNumberInput = (props: Props) => {
    const [value, setValue] = useState<number | string>(props.defaultValue || props.value || '');
    const [debounced] = useDebouncedValue(value, 200);

    useEffect(() => {
        if (!props.onChange) return;
        props.onChange(debounced);
    }, [debounced])

    useEffect(() => {
        if (!isNumber(props.value)) return;
        setValue(props.value);
    }, [props.value])

    const restProps = omit(props, ["onChange", "value"])
    return (
        <NumberInput
            value={value}
            onChange={setValue}
            {...restProps}
        />
    )
}


export default DebouncedNumberInput;