import {Box, Chip, FormControl, InputLabel, MenuItem, OutlinedInput, Select} from "@mui/material";
import moment from "jalali-moment";
import {useTranslations} from "next-intl";
import {periodOfYear} from "@/core/utils/yearPeriodFinder";

const currentShamsiYear = moment().format('jYYYY');
const shamsiYearList = Array.from({length: currentShamsiYear - 1399}, (_, index) => (currentShamsiYear - index).toString());

const YearFilter = ({formik, multiple, setFilteredText}) => {
    const t = useTranslations();
    const yearChange = (event) => {
        const {target: {value}} = event;
        formik.handleChange(event);
        formik.setFieldValue('date', value);
        const {from, to} = periodOfYear(value);
        formik.setFieldValue('from_date', from);
        formik.setFieldValue('to_date', to);
        if (Array.isArray(value)) {
            setFilteredText(prevState => ({
                ...prevState,
                year: `| ${t("filters.years")}: ${value.join(' , ')}`
            }));
        } else {
            setFilteredText(prevState => ({
                ...prevState,
                year: `| ${t("filters.year")}: ${value}`
            }));
        }
    };
    return (
        <FormControl sx={{width: 300, mx: 1, my: {xs: 1, lg: 0}}}>
            <InputLabel size="small">{t("filters.choose_year")}</InputLabel>
            <Select
                name="date"
                multiple={multiple}
                size="small"
                variant="outlined"
                value={formik.values.date}
                onChange={yearChange}
                onBlur={formik.handleBlur("date")}
                input={<OutlinedInput label={t("filters.choose_year")}/>}
                renderValue={multiple ? (selected) => (
                    <Box sx={{display: 'flex', flexWrap: 'wrap', gap: 0.5}}>
                        {selected.map((value) => (
                            <Chip key={value} label={value}
                                  sx={{color: "#fff", backgroundColor: "primary.dark"}}/>
                        ))}
                    </Box>
                ) : undefined}
            >
                {
                    shamsiYearList.map((year) => (
                        <MenuItem
                            key={year}
                            value={year}
                        >
                            {year}
                        </MenuItem>
                    ))
                }
            </Select>
        </FormControl>
    )
};

export default YearFilter;