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

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

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


const UserAuthorityCard = ({ isCollectData, updateUserAuthList, userData, isNewRecord, editMode, createMode}) => {
    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}
                border={false}
                content={false}
                sx={{margin: 0}}
            >
                <Typography variant="h6" sx={{ mt: 2, ml: 3, mr: 1, borderBottom: "1px solid black" }}>
                    User Authority
                </Typography>

                <UserAuthTable
                    userAuth={userData.authIds}
                    setSelectedRow={setSelectedRow}
                    isNewRecord={isNewRecord}
                    editMode={createMode?true:editMode}
                />
                <br/>
            </MainCard>
    );
};

export default UserAuthorityCard;
