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

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


const UserGroupCard = ({isCollectData, updateUserGroupList,userData}) => {
    const [currentUserData, setCurrentUserData] = 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) {
            setCurrentUserData(userData.data);
            setSelectedRow(userData.groupIds);
        }
    }, [userData]);

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

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


    return (
        !onReady ?
            <LoadingComponent/>
            :
            <MainCard elevation={0}
                      content={false}
            >
                <Typography variant="h5" sx={{mt: 1.5, ml: 3}}>
                    Group(s)
                </Typography>
                <UserGroupTable
                    userGroup={userData.groupIds}
                    setSelectedRow={setSelectedRow}
                />
            </MainCard>
    );
};

export default UserGroupCard;
