// material-ui
import {useState, useEffect} from 'react';
import {
    DataGrid, GridOverlay,
} from "@mui/x-data-grid";
import * as HttpUtils from "utils/HttpUtils";
import {FormattedMessage, useIntl} from "react-intl";
import {TablePagination, Typography} from '@mui/material';

// ==============================|| EVENT TABLE ||============================== //

export function FiDataGrid({ rows, columns, sx, autoHeight,
                               hideFooterSelectedRowCount, rowModesModel, editMode,
                               pageSizeOptions, filterItems, customPageSize, doLoad,  ...props }) {
    const intl = useIntl();
    const [_rows, set_rows] = useState([]);
    const [_doLoad, set_doLoad] = useState({});
    const [_columns, set_columns] = useState([]);
    const [_rowModesModel, set_rowModesModel] = useState({});
    const [_editMode, set_editMode] = useState("row");
    const [_pageSizeOptions, set_pageSizeOptions] = useState([10]);
    const [_filterItems, set_filterItems] = useState([]);

    const [page, setPage] = useState(0);
    const [pageSize, setPageSize] = useState(10);
    const [_autoHeight, set_autoHeight] = useState(true);
    const [myHideFooterSelectedRowCount, setMyHideFooterSelectedRowCount] = useState(true);
    const [_sx, set_sx] = useState({
        padding: "4 2 4 2",
        '& .MuiDataGrid-cell': {
            borderTop: 1,
            borderBottom: 1,
            borderColor: "#EEE",
        },
        '& .MuiDataGrid-footerContainer': {
            border: 1,
            borderColor: "#EEE"
        },
    });

    const [rowCount, setRowCount] = useState(0);
   
    useEffect(() => { 
        setPage(0);
        set_doLoad(doLoad); 
    }, [doLoad]);

    useEffect(()=>{
        getDataList();
    },[_doLoad, page]);


    useEffect(() => {
        if (sx) {
            set_sx(sx);
        }
        if (hideFooterSelectedRowCount) {
            setMyHideFooterSelectedRowCount(hideFooterSelectedRowCount);
        }
        if (rowModesModel) {
            set_rowModesModel(rowModesModel)
        }
        if (rows) {
            set_rows(rows)
            setRowCount(rows.length)
        }
        if (columns) {
            set_columns(columns)
        }
        if (pageSizeOptions) {
            set_pageSizeOptions(pageSizeOptions)
        }
        if(autoHeight !== undefined){
            set_autoHeight(autoHeight)
        }
        if(editMode){
            set_editMode(editMode);
        }
        if(filterItems){
            set_filterItems(filterItems);
        }
        if(customPageSize){
            setPageSize(customPageSize);
        }
    }, [sx, hideFooterSelectedRowCount, rowModesModel, rows, columns, pageSizeOptions, autoHeight, editMode, filterItems, customPageSize]);

    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };

    const handleChangePageSize = (event) => {
        setPageSize(parseInt(event.target.value, 10));
        setPage(0);
    };

    function CustomNoRowsOverlay() {
        return (
            <GridOverlay>
                <Typography variant="body1">
                    <FormattedMessage id="noRecordFound" />
                </Typography>
            </GridOverlay>
        );
    }

    
    function getDataList() {
        if(_doLoad?.url == null) return;
        if(_doLoad.params == null) _doLoad.params = {};
        _doLoad.params.start = page*pageSize;
        _doLoad.params.limit = pageSize;
        HttpUtils.get({
            url: _doLoad.url,
            params: _doLoad.params,
            onSuccess: function (responseData) {
                set_rows(responseData?.records);
                setRowCount(responseData?.count);
                if(_doLoad.callback != null){
                    _doLoad.callback(responseData);
                }
            }
        });
    }


    return (
        <DataGrid
            {...props}
            rows={_rows}
            rowCount={rowCount?rowCount:0}
            columns={_columns}
            paginationMode="server"
            disableColumnMenu
            rowModesModel={_rowModesModel}
            pageSizeOptions={_pageSizeOptions}
            editMode={_editMode}
            autoHeight={_autoHeight}
            hideFooterSelectedRowCount={myHideFooterSelectedRowCount}
            filterModel={{ items: _filterItems }}
            sx={_sx}
            components={{
                noRowsOverlay: CustomNoRowsOverlay,
                Pagination: () => (
                    <TablePagination
                        count={rowCount?rowCount:0}
                        page={page}
                        rowsPerPage={pageSize}
                        rowsPerPageOptions={_pageSizeOptions}
                        labelDisplayedRows={() =>
                            `${(_rows?.length?page*pageSize+1:0)}-${page*pageSize+(_rows?.length??0)} ${intl.formatMessage({ id: "of" })} ${rowCount}`
                        }
                        labelRowsPerPage={intl.formatMessage({ id: "rowsPerPage" }) + ":"}
                        onPageChange={handleChangePage}
                        onRowsPerPageChange={handleChangePageSize}
                    />
                ),
            }}
        />
    );
}
