// material-ui
import * as React from 'react';
import {
    DataGrid,
    GridActionsCellItem,
} from "@mui/x-data-grid";
import EditIcon from '@mui/icons-material/Edit';
import {useContext, useEffect} from "react";
import {useNavigate} from "react-router-dom";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import {
    CustomNoRowsOverlay,
    GeneralConfirmWindow,
    //getObjectById,
    notifyDeleteSuccess,
    removeObjectWithId
} from "../../utils/CommonFunction";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {GET_SEARCH_TEMPLATE_PATH} from "../../utils/ApiPathConst";
import UploadContext from "../../components/UploadProvider";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";

export default function DivisionTable({recordList}) {
    const [rows, setRows] = React.useState(recordList);
    const [rowModesModel] = React.useState({});
    const navigate = useNavigate();
    const { setIsUploading } = useContext(UploadContext);

// ==============================|| DELETE WINDOW RELATED ||============================== //
    const [isWindowOpen, setIsWindowOpen] = React.useState(false);
    const [selectedId, setSelectedId] = React.useState(null);

    const handleClose = () => {
        setIsWindowOpen(false);
    };

    const [paginationModel, setPaginationModel] = React.useState({
        page: 0,
        pageSize:10
    });
    useEffect(() => {
        setPaginationModel({page:0,pageSize:10});
        setRows(recordList);
    }, [recordList]);

    const handleDeleteClick = (id) => () => {
        setIsWindowOpen(true);
        setSelectedId(id);
    };

    function updateData(){
        setIsUploading(true);
        axios.delete(`${apiPath}${GET_SEARCH_TEMPLATE_PATH}/${selectedId}`,
        )
            .then((response) => {
                if (response.status === 204) {
                    notifyDeleteSuccess();
                    const newList =removeObjectWithId(rows,selectedId);
                    setIsWindowOpen(false);
                    setRows(newList);
                }
                setIsUploading(false);
            })
            .catch(error => {
                console.log(error);
                setIsUploading(false);
                return false;
            });
    }
// ==============================|| DELETE WINDOW RELATED ||============================== //

    const handleEditClick = (id) => () => {
        navigate('/template/maintain/'+ id);
    };

    const columns = [
        {
            field: 'actions',
            type: 'actions',
            headerName: 'Actions',
            width: 100,
            cellClassName: 'actions',
            getActions: ({id}) => {
                return [
                    <ThemeProvider key="OutSave" theme={LIONER_BUTTON_THEME}>
                    <GridActionsCellItem
                        key="OutDelete"
                        icon={<DeleteIcon sx={{fontSize: 25}}/>}
                        label="Delete"
                        onClick={handleDeleteClick(id)}
                        color="delete"
                    />
                    </ThemeProvider>,
                    <ThemeProvider key="OutSave" theme={LIONER_BUTTON_THEME}>
                    <GridActionsCellItem
                        key="OutSave"
                        icon={<EditIcon sx={{fontSize: 25}}/>}
                        label="Edit"
                        className="textPrimary"
                        onClick={handleEditClick(id)}
                        color="edit"
                    />
                    </ThemeProvider>,
                ]
            },
        },
        {
            id: 'module',
            field: 'module',
            headerName: 'Module',
            flex: 1,
        },
        {
            id: 'templateName',
            field: 'name',
            headerName: 'Template Name',
            flex: 1,
        },
    ];

    return (
        <div style={{/*height: '59vh',*/ width: '100%'}}>
            <DataGrid
                rows={rows}
                columns={columns}
                columnHeaderHeight={45}
                editMode="row"
                rowModesModel={rowModesModel}
                getRowHeight={() => 'auto'}
                paginationModel={paginationModel}
                onPaginationModelChange={setPaginationModel}
                slots={{
                    noRowsOverlay: () => (
                        CustomNoRowsOverlay()
                    )
                }}
                pageSizeOptions={[10]}
                autoHeight
            />
            <GeneralConfirmWindow
                isWindowOpen={isWindowOpen}
                title={"Attention"}
                content={`Are you sure to delete?`}
                //content={`Are you sure to delete? ${getObjectById(rows,selectedId) === null? "" : '"' + getObjectById(rows,selectedId).name + '"'} ?`}
                onNormalClose={handleClose}
                onConfirmClose={updateData}
            />
        </div>
    );
}
