import {Button, CircularProgress} from "@mui/material";
import {useTranslations} from "next-intl";
import {useMemo, useState} from "react";
import useRequest from "@/lib/app/hooks/useRequest";
import {EXPORT_MACHINARY_OFFICE} from "@/core/data/apiRoutes";
import moment from "jalali-moment";
import FileSaver from 'file-saver';
import DescriptionIcon from '@mui/icons-material/Description';

const PrintExcel = ({table}) => {
    const t = useTranslations();
    const [loading, setLoading] = useState(false)
    const requestServer = useRequest({auth: true, pending: false, success: {notification: {show: false}}})
    const {columnFilters, columnFilterFns, sorting} = table.getState()
    const columns = table.getAllColumns()

    const filterParams = useMemo(() => {
        const params = new URLSearchParams();
        const filters = columnFilters.map((filter) => {
            let datatype;
            for (const i in columns) {
                if (columns[i].id == filter.id) {
                    datatype = columns[i].columnDef.datatype;
                }
            }
            return {
                ...filter, fn: columnFilterFns[filter.id], datatype: datatype,
            };
        });
        params.set("start", '0');
        params.set("filters", JSON.stringify(filters ?? []));
        params.set("sorting", JSON.stringify(sorting ?? []));
        return params;
    }, [columnFilters, columnFilterFns, sorting, columns,]);


    const clickHandler = () => {
        setLoading(true)
        requestServer(`${EXPORT_MACHINARY_OFFICE}?${filterParams}`, 'get', {
            auth: true,
            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"
            size="small"
            disabled={loading}
            sx={{textTransform: "unset", alignSelf: "center"}}
            startIcon={loading ? <CircularProgress size={18} color="inherit"/> : <DescriptionIcon/>}
            onClick={clickHandler}
        >
            {t("MachinaryOffice.excel_report")}
        </Button>
    )
}

export default PrintExcel