import {Grid, TextField} from '@mui/material';
import {useEffect} from "react";

const BetweenNumberFilter = ({formik, id ,  defaultValue}) => {

    useEffect(() => {
        formik.setFieldValue(`${id}[0]`, defaultValue?.[0] || '');
        formik.setFieldValue(`${id}[1]`, defaultValue?.[1] || '');
    }, []);
    const handleBlur = (index) => () => {
        const minValue = formik.values[id][0];
        const maxValue = formik.values[id][1];

        if (index === 0 && minValue !== '' && maxValue !== '' && parseInt(minValue) > parseInt(maxValue)) {
            formik.setFieldValue(`${id}[0]`, maxValue);
        }

        if (index === 1 && minValue !== '' && maxValue !== '' && parseInt(maxValue) < parseInt(minValue)) {
            formik.setFieldValue(`${id}[1]`, minValue);
        }
    };
    return (
        <Grid container spacing={2}>
            <Grid item xs={6}>
                <TextField
                    name={`${id}[0]`}
                    label="کمترین رقم"
                    id={`${id}_min`}
                    onChange={formik.handleChange}
                    onBlur={handleBlur(0)}
                    fullWidth
                    value={formik.values[id][0] || ''}
                    margin="normal"
                    sx={{
                        position: 'relative'
                    }}
                />
            </Grid>
            <Grid item xs={6}>
                <TextField
                    name={`${id}[1]`}
                    label="بیشترین رقم"
                    id={`${id}_max`}
                    onChange={formik.handleChange}
                    onBlur={handleBlur(1)}
                    fullWidth
                    value={formik.values[id][1] || ''}
                    margin="normal"
                    sx={{
                        position: 'relative'
                    }}
                />
            </Grid>
        </Grid>
    );
};

export default BetweenNumberFilter;
