import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material";
import { useMemo, useState } from "react";
import moment from "jalali-moment";
import FileSaver from "file-saver";
import DescriptionIcon from "@mui/icons-material/Description";
import useRequest from "@/lib/hooks/useRequest";
import { EXPORT_FAST_REACT_OPERATOR_LIST } from "@/core/utils/routes";
import { useTheme } from "@emotion/react";
import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure";
import isArrayEmpty from "@/core/utils/isArrayEmpty";

const PrintExcel = ({ table, filterData }) => {
    const [loading, setLoading] = useState(false);
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
    const requestServer = useRequest();
    const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => {
        if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) {
            acc.push({ id: key, value: filter.value });
        }
        return acc;
    }, []);

    const filterParams = useMemo(() => {
        const params = new URLSearchParams();
        if (activeFilters.length > 0) {
            activeFilters.map((filter, index) => {
                const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty);
                params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData));
            });
        } else {
            params.set("filters", JSON.stringify([]));
        }
        return params;
    }, [activeFilters]);

    const clickHandler = () => {
        setLoading(true);
        requestServer(`${EXPORT_FAST_REACT_OPERATOR_LIST}?${filterParams}`, "get", {
            requestOptions: { responseType: "blob" },
        })
            .then((response) => {
                const filename = `خروجی کارتابل عملیات واکنش سریع تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`;
                FileSaver.saveAs(response.data, filename);
            })
            .catch(() => {})
            .finally(() => {
                setLoading(false);
            });
    };

    return (
        <>
            {isMobile ? (
                <IconButton aria-label="خروجی اکسل" color="success" onClick={clickHandler}>
                    <DescriptionIcon sx={{ fontSize: "25px" }} />
                </IconButton>
            ) : (
                <Button
                    color="success"
                    variant="contained"
                    size="small"
                    disabled={loading}
                    sx={{ textTransform: "unset", alignSelf: "center" }}
                    startIcon={loading ? <CircularProgress size={18} color="inherit" /> : <DescriptionIcon />}
                    onClick={clickHandler}
                >
                    خروجی اکسل
                </Button>
            )}
        </>
    );
};

export default PrintExcel;
