// material-ui
import {
    DataGrid, GridActionsCellItem,
} from "@mui/x-data-grid";
import {useEffect, useState} from "react";
import LoadingComponent from "../extra-pages/LoadingComponent";
import * as React from "react";
import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import {removeObjectWithId} from "../../utils/CommonFunction";

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

export default function UserAddTable({setGroupUserData, userList}) {
    const [groupData, setGroupData] = useState([]);
    const [onReady, setOnReady] = useState(false);

    useEffect(() => {
        setGroupData(userList);
    }, []);

    useEffect(() => {
        setGroupData(userList);
    }, [userList]);

    useEffect(() => {
        //if state data are ready and assign to different field
        if (groupData !== undefined) {
            setOnReady(true);
        }
    }, [groupData]);

    const handleDeleteClick = (id) => () => {
        const newList =removeObjectWithId(groupData,id)
        setGroupUserData(newList);
        setGroupData(newList);
    };

    const columns = [
        {
            field: 'actions',
            type: 'actions',
            headerName: 'Actions',
            width: 100,
            cellClassName: 'actions',
            getActions: ({id}) => {
                return [
                    <GridActionsCellItem
                        key="OutDelete"
                        icon={<DeleteIcon/>}
                        label="Delete"
                        onClick={handleDeleteClick(id)}
                        color="inherit"
                    />,
                    ]
            },
        },
        {
            id: 'name',
            field: 'name',
            headerName: 'User',
            flex: 1,
        },
        {
            id: 'subDiv',
            field: 'subDivisionName',
            headerName: 'Sub-Division',
            flex: 1,
        },
    ];

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <div style={{height: '100%', width: '100%', overflow: "auto" }}>
                <DataGrid
                    rows={groupData}
                    columns={columns}
                    editMode="row"
                    initialState={{
                        pagination: {
                            paginationModel: {page: 0, pageSize: 3},
                        },
                    }}
                    pageSizeOptions={[3, 5]}
                    pageSize={20}
                    autoHeight={true}
                />
            </div>
    );
}
