import debounce from 'lodash.debounce';
import { useState, useMemo } from 'react';

import TextField from '@mui/material/TextField';
// ----------------------------------------------------------------------

type NumFilterProps = {
    label: string;
    onChange?: (value: string) => void;
}

const isNumbers = (str: string) => /^[0-9]*$/.test(str);

export function IntFilter({ label, onChange }: NumFilterProps) {
    const [val, setVal] = useState("");

    const onInputChange = (event: any) => {
        const value = event.target.value;
        if (isNumbers(value)) {
            setVal(value);
            debouncedChange(value);
        }
    };

    const debouncedChange = useMemo(() =>
        debounce((value: string) => {
            onChange?.(value);
        }, 1000)
        , [onChange]);

    return <TextField label={label} value={val} onChange={onInputChange} variant="filled" />;
}

export function DecimalFilter({ label, onChange }: NumFilterProps) {
    const debouncedChange = useMemo(() =>
        debounce((value: string) => {
            onChange?.(value);
        }, 1000)
        , [onChange]);

    return <TextField type="number" label={label} variant="filled" onChange={e => debouncedChange(e.target.value)} />;
}