// material-ui
import {
    Button,
    Grid, TextField,
    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 UserAddTable from "./UserAddTable";
import {GET_GROUP_MEMBER_LIST_PATH, GET_USER_COMBO_LIST} from "../../utils/ApiPathConst";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import Autocomplete from "@mui/material/Autocomplete";
import {getIdList} from "../../utils/CommonFunction";
import {ThemeProvider} from "@emotion/react";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const UserAddCard = ({isCollectData, updateGroupMember,userGroupData,isNewRecord}) => {
    const [currentUserData, setCurrentUserData] = React.useState({});
    const [onReady, setOnReady] = useState(false);
    const [groupUserData, setGroupUserData] = useState([]);
    const [userComboList, setUserComboList] = useState([]);
    const [selectedUser, setSelectedUser] = useState(null);
    const [deletedList, setDeletedList] = useState([]);

    function updateUserList (){
        const idList = getIdList(groupUserData);
        if(!idList.includes(selectedUser.id)){
            const userList = [...groupUserData, selectedUser];
            setGroupUserData(userList);
        }
    }

    useEffect(() => {
        axios.get(`${apiPath}${GET_USER_COMBO_LIST}`)
            .then((response) => {
                if (response.status === 200) {
                    setUserComboList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }, []);

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

    useEffect(() => {
        //if state data are ready and assign to different field
        if(isNewRecord){
            setOnReady(true);
        }
        else{
            if (Object.keys(userGroupData).length > 0 &&currentUserData !== undefined) {
                axios.get(`${apiPath}${GET_GROUP_MEMBER_LIST_PATH}?id=${userGroupData.data.id}`)
                    .then((response) => {
                        if (response.status === 200) {
                            setGroupUserData(response.data.records);
                        }
                        setOnReady(true);
                    })
                    .catch(error => {
                        console.log(error);
                        return false;
                    });
            }
        }
    }, [currentUserData]);

    useEffect(() => {
        //upload latest data to parent
        updateGroupMember({
            "currentList" : groupUserData,
            "deletedList" : deletedList
        });
    }, [isCollectData]);


    return (
        !onReady ?
            <LoadingComponent/>
            :
            <MainCard elevation={0}
                      content={false}
            >
                <Typography variant="h5" sx={{mt: 3, ml: 3}}>
                    User(s)
                </Typography>
                <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mt: 2}}>
                    <Grid container alignItems={"center"}>
                        <Grid item xs={3} s={3} md={2} lg={2}
                              sx={{display: 'flex', alignItems: 'center'}}>
                            <Typography variant="lionerSize" component="span">
                                User:
                            </Typography>
                        </Grid>
                        <Grid item xs={6} s={5} md={5} lg={5}>
                            <Autocomplete
                                disablePortal
                                size="small"
                                id="user-combo"
                                value={selectedUser === null ? null : selectedUser}
                                options={userComboList}
                                onChange={(event, newValue) => {
                                    setSelectedUser(newValue);
                                }}
                                renderInput={(params) => <TextField {...params} />}
                            />
                        </Grid>
                        <Grid item xs={3} s={3} md={4} lg={4} sx={{ml: 3}}>
                            <ThemeProvider theme={LIONER_BUTTON_THEME}>
                                <Button
                                    variant="contained"
                                    type="submit"
                                    color="save"
                                    onClick={updateUserList}
                                >
                                    Add
                                </Button>
                            </ThemeProvider>
                        </Grid>
                    </Grid>
                </Grid>

                <UserAddTable
                    setGroupUserData={setGroupUserData}
                    setDeletedList={setDeletedList}
                    userList={groupUserData}
                />
            </MainCard>
    );
};

export default UserAddCard;
