// 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 { GET_GROUP_MEMBER_LIST_PATH, GET_USER_GLD_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 LoadingComponent from "../extra-pages/LoadingComponent";
//import UserAddTable from "./UserAddTable";
import Loadable from 'components/Loadable';
import { lazy } from 'react';
const LoadingComponent = Loadable(lazy(() => import('../extra-pages/LoadingComponent')));
const UserAddTable = Loadable(lazy(() => import('./UserAddTable')));

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


const UserAddCard = ({ isCollectData, updateGroupMember, userGroupData, isNewRecord, editMode }) => {
    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([]);
    const [_editMode, setEditMode] = useState(editMode);

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

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

    useEffect(() => {
        axios.get(`${apiPath}${GET_USER_GLD_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}
                border={false}
                content={false}
            >
                <Typography variant="h4" sx={{ mt: 3, ml: 3, mb: 2, mr: 3, borderBottom: "1px solid black" }}>
                    User(s)
                </Typography>

                {
                    _editMode ?
                        <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="h5">User:</Typography>
                                </Grid>
                                <Grid item xs={6} s={5} md={5} lg={5}>
                                    <Autocomplete
                                        disablePortal
                                        id="user-combo"
                                        value={selectedUser === null ? null : selectedUser}
                                        options={userComboList}
                                        getOptionLabel={(option) => {
                                            if (option == null) return "";
                                            if (typeof option === "string") return option;
                                            const s = option.label ?? option.name ?? option.username ?? option.fullName ?? option.enName;
                                            return s != null ? String(s) : "";
                                        }}
                                        onChange={(event, newValue) => {
                                            // console.log(newValue)
                                            setSelectedUser(newValue);
                                        }}
                                        sx={{
                                            '& .MuiInputBase-root': { alignItems: 'center' },
                                            '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                            '& .MuiOutlinedInput-root': { height: 40 }
                                        }}
                                        renderInput={(params) => <TextField {...params} />}
                                    />
                                </Grid>
                                <Grid item xs={3} s={3} md={4} lg={4} sx={{ ml: 3 }}>
                                    <Button
                                        size="large"
                                        variant="contained"
                                        type="submit"
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end'
                                        }}
                                        onClick={updateUserList}
                                    >
                                        <Typography variant="h5">Add</Typography>
                                    </Button>
                                </Grid>
                            </Grid>
                        </Grid>
                        : <></>
                }


                <Grid container>
                    <Grid item xs={12}>
                        <UserAddTable
                            setGroupUserData={setGroupUserData}
                            setDeletedList={setDeletedList}
                            userList={groupUserData}
                            editMode={_editMode}
                        />
                    </Grid>
                </Grid>
            </MainCard>
    );
};

export default UserAddCard;
