// material-ui
import {
    Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import * as React from "react";
import {useEffect, useState} from "react";
import LoadingComponent from "../extra-pages/LoadingComponent";
import GroupAuthTable from "./GroupAuthTable";

// ==============================|| DASHBOARD - DEFAULT ||============================== //


const GroupAuthCard = ({isCollectData, updateUserAuthList,userGroupData}) => {
    const [currentAuthData, setCurrentAuthData] = React.useState({});
    const [onReady, setOnReady] = useState(false);
    const [selectedRow, setSelectedRow] = useState([]);
    const [referenceRow, setReferenceRow] = useState([]);

    useEffect(() => {
        //if user data from parent are not null
        if (Object.keys(userGroupData).length > 0 && userGroupData !== undefined) {
            setCurrentAuthData(userGroupData.data);
            setSelectedRow(userGroupData.authIds);
            setReferenceRow(userGroupData.authIds);
        }
    }, [userGroupData]);

    useEffect(() => {
        //if state data are ready and assign to different field
        if (Object.keys(userGroupData).length > 0 && currentAuthData !== undefined) {
            setOnReady(true);
        }
    }, [currentAuthData]);

    useEffect(() => {
        //upload latest data to parent
        let deletedList = referenceRow.filter(x => !selectedRow.includes(x));
        updateUserAuthList({
            "currentList": selectedRow,
            "deletedList": deletedList
        });
    }, [isCollectData]);


    return (
        !onReady ?
            <LoadingComponent/>
            :
            <MainCard elevation={0}
                      content={false}
            >
                <Typography variant="h5" sx={{mt: 1.5, ml: 1.5}}>
                    User Authority
                </Typography>

                <GroupAuthTable
                    userAuth={userGroupData.authIds}
                    setSelectedRow={setSelectedRow}
                />
            </MainCard>
    );
};

export default GroupAuthCard;
