import {
    Accordion,
    AccordionDetails,
    AccordionSummary,
    Box,
    Button,
    CircularProgress,
    IconButton,
    Stack,
    Tooltip,
    Typography
} from "@mui/material";
import {useFormik} from "formik";
import ProvinceFilter from "../Filter/ProvinceFilter";
import YearFilter from "../Filter/YearFilter";
import FilterAltIcon from '@mui/icons-material/FilterAlt';
import EqualizerIcon from '@mui/icons-material/Equalizer';
import {useTranslations} from "next-intl";
import TroubleshootIcon from '@mui/icons-material/Troubleshoot';
import CachedIcon from '@mui/icons-material/Cached';
import {useEffect, useState} from "react";
import moment from "jalali-moment";
import {periodOfYear} from "@/core/utils/yearPeriodFinder";

const Filter = ({title, filterItem, setFilterOption, isLoadingReportList, mutate}) => {
    const t = useTranslations();
    const filter_by_province = filterItem.find((item) => item.type === "province");
    const filter_by_year = filterItem.find((item) => item.type === "year");

    const [expanded, setExpanded] = useState(false);
    const [filteredText, setFilteredText] = useState({province: "", year: ""});
    const [stepValue, setStepValue] = useState({
        ...(filter_by_year && {
            date: filter_by_year.multiple ? [] : `${moment().format('jYYYY')}`
        }),
        ...(filter_by_province && {
            province_id: filter_by_province.multiple ? [] : ""
        }),
        from_date: periodOfYear(moment().format('jYYYY')).from,
        to_date: periodOfYear(moment().format('jYYYY')).to
    })


    const formik = useFormik({
        enableReinitialize: true,
        initialValues: stepValue, onSubmit: (values, {setSubmitting}) => {
            setStepValue(values)
            const province = values.province_id;
            const fields = [
                values.from_date ? {key: "from_date", value: values.from_date} : null,
                values.to_date ? {key: "to_date", value: values.to_date} : null,
                ...(Array.isArray(province)
                        ? province.length !== 0
                            ? province.map((item, index) => ({key: `province_id[${index}]`, value: item}))
                            : []
                        : province
                            ? [{key: "province_id", value: province}]
                            : []
                ),
            ].filter(Boolean);
            setFilterOption(fields)
        },
    });

    useEffect(() => {
        const province = formik.values.province_id;
        const fields = [
            formik.values.from_date ? {key: "from_date", value: formik.values.from_date} : null,
            formik.values.to_date ? {key: "to_date", value: formik.values.to_date} : null,
            ...(Array.isArray(province)
                    ? province.length !== 0
                        ? province.map((item, index) => ({key: `province_id[${index}]`, value: item}))
                        : []
                    : province
                        ? [{key: "province_id", value: province}]
                        : []
            ),
        ].filter(Boolean);
        setFilterOption(fields)
    }, []);

    return (
        <Accordion elevation={0} expanded={expanded} onChange={() => {
        }} sx={{
            mb: 2,
            borderBottom: 2,
            borderBottomColor: "divider",
            backgroundColor: "#f1f1f1",
        }}>
            <AccordionSummary sx={{cursor: "unset !important"}}>
                <Box sx={{width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between"}}>
                    <Box sx={{display: "flex", alignItems: "center", gap: 0.5}}>
                        <EqualizerIcon sx={{color: "primary.main"}}/>
                        <Typography sx={{fontWeight: 500, color: "primary.main"}}>{title}</Typography>
                        <Typography variant="caption" sx={{fontWeight: 500}} color="error">
                            {filteredText.province} {filteredText.year}
                        </Typography>
                    </Box>
                    <Box>
                        <Tooltip title={t("filters.update_again")} arrow>
                            <IconButton onClick={() => mutate()}
                                        size="small">
                                <CachedIcon color="primary"/>
                            </IconButton>
                        </Tooltip>
                        <Tooltip title={t("filters.filter_btn")} arrow>
                            <IconButton onClick={() => setExpanded((prevExpanded) => !prevExpanded)}
                                        size="small">
                                <FilterAltIcon color="primary"/>
                            </IconButton>
                        </Tooltip>
                    </Box>
                </Box>
            </AccordionSummary>
            <AccordionDetails sx={{
                display: "flex",
                flexDirection: {xs: "column", sm: "row"},
                justifyContent: "space-between",
                alignItems: "center"
            }}>
                <Stack sx={{flexDirection: {xs: "column", sm: "row"}, alignItems: "center", flexWrap: 'wrap'}}>
                    {filter_by_province ?
                        <ProvinceFilter formik={formik} multiple={filter_by_province.multiple}
                                        setFilteredText={setFilteredText}/> : ""
                    }
                    {filter_by_year ?
                        <YearFilter formik={formik} multiple={filter_by_year.multiple}
                                    setFilteredText={setFilteredText}/> : ""
                    }
                </Stack>
                <Stack>
                    <Button onClick={formik.handleSubmit} variant="contained"
                            disabled={isLoadingReportList || !formik.dirty}
                            startIcon={isLoadingReportList ?
                                <CircularProgress size={20} color="inherit"/> :
                                <TroubleshootIcon/>}
                    >{t("filters.filter")}</Button>
                </Stack>
            </AccordionDetails>
        </Accordion>
    )
};

export default Filter;