// 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";

import Loadable from 'components/Loadable';
import { lazy } from 'react';
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));

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


const UserGroupCard = ({isCollectData, updateUserGroupList,userData,isNewRecord,editMode,createMode}) => {
    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) {
            // console.log(userData.groupIds)
            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}
                      border={false}
                      content={false}
                      sx={{margin: 0}}
            >
                <Typography variant="h6" sx={{mt: 2, ml: 3, mr: 1, borderBottom: "1px solid black"}}>
                    Group(s)
                </Typography>
                <UserGroupTable
                    userGroup={userData.groupIds}
                    setSelectedRow={setSelectedRow}
                    isNewRecord={isNewRecord}
                    editMode={createMode?true:editMode}
                />
                <br/>
            </MainCard>
    );
};

export default UserGroupCard;
