// 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 UserAuthTable from "./UserAuthTable";

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


const UserAuthorityCard = ({isCollectData, updateUserAuthList,userData}) => {
    const [currentAuthData, setCurrentAuthData] = React.useState({});
    const [onReady, setOnReady] = useState(false);
    const [selectedRow, setSelectedRow] = useState([]);

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

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

    useEffect(() => {
        //upload latest data to parent
        updateUserAuthList(selectedRow);
    }, [isCollectData]);


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

                <UserAuthTable
                    userAuth={userData.authIds}
                    setSelectedRow={setSelectedRow}
                />
            </MainCard>
    );
};

export default UserAuthorityCard;
