import {
    Accordion,
    AccordionDetails,
    AccordionSummary,
    Box,
    Button,
    CircularProgress,
    Stack,
    Typography
} from "@mui/material";
import FileUploadIcon from '@mui/icons-material/FileUpload';
import AssignmentIcon from '@mui/icons-material/Assignment';
import BackupIcon from '@mui/icons-material/Backup';
import {useTranslations} from "next-intl";
import ProvinceFilter from "@/components/dashboard/old-reports/Filter/ProvinceFilter";
import YearFilter from "@/components/dashboard/old-reports/Filter/YearFilter";
import {useState} from "react";
import {useFormik} from "formik";
import {GET_EXPORT} from "@/core/data/apiRoutes";
import moment from "jalali-moment";
import FileSaver from 'file-saver';
import useRequest from "@/lib/app/hooks/useRequest";
import {periodOfYear} from "@/core/utils/yearPeriodFinder";

const ExcelExport = () => {
    const t = useTranslations();
    const requestServer = useRequest()
    const filterItem = [
        {type: "province", type_fa: "استان", multiple: false},
        {type: "year", type_fa: "سال", multiple: false}
    ];
    const filter_by_province = filterItem.find((item) => item.type === "province");
    const filter_by_year = filterItem.find((item) => item.type === "year");

    const [filteredText, setFilteredText] = useState({province: "", year: ""});

    const formik = useFormik({
        initialValues: {
            ...(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
        }, onSubmit: (values, {setSubmitting}) => {
            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);
            const queryString = fields.length !== 0
                ? `?${fields.map((option) => `${option.key}=${option.value}`).join('&')}`
                : '';
            setSubmitting(true)
            requestServer(`${GET_EXPORT}${queryString}`, 'GET', {
                auth: true,
                notification: false,
                requestOptions: {responseType: 'blob'}
            })
                .then((response) => {
                    const filename = `گزارش درخواست های وام ناوگان تاریخ_${moment().format('jYYYY_jMM_jDD')}.xlsx`;
                    FileSaver.saveAs(response.data, filename);
                }).catch(() => {
            }).finally(() => {
                setSubmitting(false);
            });
        },
    });

    return (
        <Stack sx={{width: "95%", mx: "auto"}}>
            <Accordion elevation={0} sx={{
                width: "100%",
                mb: 2,
                borderBottom: 2,
                borderBottomColor: "divider",
                backgroundColor: "#f1f1f1"
            }}>
                <AccordionSummary>
                    <Box sx={{width: "100%", display: "flex", alignItems: "center", justifyContent: "space-between"}}>
                        <Box sx={{display: "flex", alignItems: "center", gap: 0.5}}>
                            <AssignmentIcon sx={{color: "primary.main"}}/>
                            <Typography sx={{fontWeight: 500, color: "primary.main"}}>
                                {t("filters.excel_export")}
                            </Typography>
                        </Box>
                        <FileUploadIcon sx={{color: "primary.main"}}/>
                    </Box>
                </AccordionSummary>
                <AccordionDetails
                    sx={{
                        display: "flex",
                        flexDirection: {xs: "column", sm: "row"},
                        justifyContent: "space-between",
                        alignItems: "center",
                        mx: "auto",
                    }}>
                    <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={formik.isSubmitting}
                                sx={{backgroundColor: "success.main"}}
                                startIcon={formik.isSubmitting ?
                                    <CircularProgress size={20} color="inherit"/> :
                                    <BackupIcon/>}
                        >
                            {t("filters.export")}
                        </Button>
                    </Stack>
                </AccordionDetails>
            </Accordion>
        </Stack>
    )
};

export default ExcelExport;