import { useState } from "react"
import { Box, Button } from "@mui/material"
import axiosInstance from "../http/axiosInstance"
import { DataGrid } from "@mui/x-data-grid"

export default function Reports() {
    const [state, setState] = useState(null)

    const fetch = async () => {
        await axiosInstance.get(`/info/reports/0?to_export=true`, {
            responseType: 'blob',
        }).then(response => {
            const url = window.URL.createObjectURL(response.data)
            const link = document.createElement('a')
            link.href = url
            link.setAttribute('download', 'report.xlsx')
            document.body.appendChild(link);
            link.click();
            link.remove();
        })
    }

    const fetchBlob = async () => {
        await axiosInstance.get(`/info/reports/0`).then(response => {
            setState(JSON.parse(response.data))
        })
    }

    return (
        <>
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                <Box>
                    <Button onClick={() => fetchBlob()}>
                        Получить отчет
                    </Button>

                    <Button onClick={() => fetch()}>
                        Экспорт
                    </Button>
                </Box>

                {state &&
                    <DataGrid
                        autoHeight
                        style={{ width: "100%" }}
                        rows={[...new Set(Object.keys(state).flatMap(key => Object.keys(state[key])))].map(id => {
                            const row: any = { id: Number(id) };
                            Object.keys(state).forEach(key => {
                                row[key] = state[key][id];
                            });
                            return row;
                        })}
                        columns={[
                            { field: 'id', headerName: '№', width: 70 },
                            ...Object.keys(state).map(key => ({
                                field: key,
                                headerName: key.charAt(0).toUpperCase() + key.slice(1),
                                width: 150
                            }))
                        ]}
                        initialState={{
                            pagination: {
                                paginationModel: { page: 0, pageSize: 10 },
                            },
                        }}
                        pageSizeOptions={[10, 20, 50, 100]}
                        checkboxSelection={false}
                        disableRowSelectionOnClick

                        processRowUpdate={(updatedRow, originalRow) => {
                            return updatedRow
                        }}

                        onProcessRowUpdateError={(error) => {
                        }}
                    />
                }
            </Box>
        </>
    )
}