// 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 LoadingComponent = Loadable(lazy(() => import('../extra-pages/LoadingComponent')));
const GroupAuthTable = Loadable(lazy(() => import('./GroupAuthTable')));

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

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

    useEffect(()=>{
        setEditMode(editMode);
    },[editMode])

    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}
                      border={false}
                      content={false}
            >
                <Typography variant="h4" sx={{ mt: 3, ml: 3, mb: 2, mr: 3, borderBottom: "1px solid black" }}>
                    User Authority
                </Typography>

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

export default GroupAuthCard;
