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

const PrintExcel = ({ table, filterData }) => {
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
    const [loading, setLoading] = useState(false);
    const requestServer = useRequest({ notificationSuccess: true });
    const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => {
        if (filter.value) {
            acc.push({ id: filter.id, 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);
        const CountryOrProvince = activeFilters.find((item) => item.id === "province_id");
        const requestUrl =
            CountryOrProvince.value === "-1" ? EXPORT_COUNTRY_RECEIPT_REPORT : EXPORT_PROVINCE_RECEIPT_REPORT;
        requestServer(`${requestUrl}?${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="primary" onClick={clickHandler}>
                    <DescriptionIcon sx={{ fontSize: "25px" }} />
                </IconButton>
            ) : (
                <Button
                    color="primary"
                    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;
