import {Accordion, AccordionSummary, Box, Button, CircularProgress, Stack, Typography} from "@mui/material";
import AssignmentIcon from '@mui/icons-material/Assignment';
import BackupIcon from '@mui/icons-material/Backup';
import {useTranslations} from "next-intl";
import {GET_EXCEL_EXPORT} from "@/core/data/apiRoutes";
import moment from "jalali-moment";
import FileSaver from 'file-saver';
import useRequest from "@/lib/app/hooks/useRequest";
import {useState} from "react";

const ExcelExport = () => {
    const t = useTranslations();
    const requestServer = useRequest();
    const [loading, setLoading] = useState(false);

    const clickHandler = () => {
        setLoading(true)
        requestServer(GET_EXCEL_EXPORT, 'get', {
            auth: true,
            requestOptions: {responseType: 'blob'}
        }).then((response) => {
            const filename = `گزارش عملکرد_${moment().format('jDD_jMM_jYYYY')}.xlsx`;
            FileSaver.saveAs(response.data, filename);
        }).catch(() => {
        }).finally(() => {
            setLoading(false)
        })
    }

    return (
        <Stack sx={{width: "95%", mx: "auto"}}>
            <Accordion elevation={0} sx={{
                width: "100%",
                mb: 2,
                borderBottom: 2,
                borderBottomColor: "divider",
                backgroundColor: "#f1f1f1",
            }} expanded={false}>
                <AccordionSummary sx={{cursor: "unset !important"}}>
                    <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_reports")}
                            </Typography>
                        </Box>
                        <Button onClick={clickHandler} variant="contained"
                                sx={{backgroundColor: "success.main"}}
                                disabled={loading}
                                startIcon={loading ?
                                    <CircularProgress size={20} color="inherit"/> :
                                    <BackupIcon/>}
                        >
                            {t("filters.export")}
                        </Button>
                    </Box>
                </AccordionSummary>
            </Accordion>
        </Stack>
    )
};

export default ExcelExport;