import { Button, CircularProgress } 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_ROAD_PATROL_OPERATOR_LIST } from "@/core/utils/routes";

const PrintExcel = ({ table, filterData }) => {
    const [loading, setLoading] = useState(false);
    const requestServer = useRequest();
    const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => {
        if (filter.value) {
            // Check if there's an active filter
            acc.push({ id: key, value: filter.value });
        }
        return acc;
    }, []);

    const filterParams = useMemo(() => {
        const params = new URLSearchParams();
        activeFilters.length > 0 &&
            activeFilters.map((filter, index) => {
                params.set(`${filter.id}`, filter.value);
            });
        return params;
    }, [activeFilters]);

    const clickHandler = () => {
        setLoading(true);
        requestServer(`${EXPORT_ROAD_PATROL_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 (
        <Button
            color="primary"
            variant="contained"
            disabled={loading}
            sx={{ textTransform: "unset", alignSelf: "center" }}
            startIcon={loading ? <CircularProgress size={18} color="inherit" /> : <DescriptionIcon />}
            onClick={clickHandler}
        >
            خروجی اکسل
        </Button>
    );
};

export default PrintExcel;
