// material-ui
import {
    Button,
    Grid, Typography
} from '@mui/material';
import {useContext, useEffect, useState} from "react";
import * as React from "react";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {useParams} from "react-router-dom";
import LoadingComponent from "../extra-pages/LoadingComponent";
import {GET_GROUP_LIST_PATH, UPDATE_GROUP_PATH} from "../../utils/ApiPathConst";
import GroupAuthCard from "./GroupAuthCard";
import UserGroupInfoCard from "./UserGroupInfoCard";
import UserAddCard from "./UserAddCard";
import {
    GeneralConfirmWindow,
    getDeletedRecordWithRefList,
    getIdList,
    notifyDeleteSuccess,
    notifySaveSuccess
} from "../../utils/CommonFunction";
import {useNavigate} from "react-router";
import UploadContext from "../../components/UploadProvider";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";

import {LIONER_FORM_THEME} from "../../themes/themeConst";

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


const UserMaintainPage = () => {
    const { setIsUploading } = useContext(UploadContext);

    const params = useParams();
    const navigate = useNavigate();
    const [onReady, setOnReady] = useState(false);
    const [isCollectData, setIsCollectData] = useState(false);
    const [editedGroupData, setEditedGroupData] = useState({});
    const [userGroupData,setUserGroupData] = useState({});
    const [userAuthData,setUserAuthData] = useState([]);
    const [userConfirm, setUserConfirm] = useState(false);
    const [groupMember, setGroupMember] = useState([]);
    const [isNewRecord, setIsNewRecord] = useState(false);
    const [deletedUserList, setDeletedUserList] = React.useState([]);
    const [deletedAuthList, setDeletedAuthList] = React.useState([]);

// ==============================|| DELETE WINDOW RELATED ||============================== //
    const [isWindowOpen, setIsWindowOpen] = React.useState(false);
    const handleClose = () => {
        setIsWindowOpen(false);
    };

    const handleDeleteClick = () => {
        setIsWindowOpen(true);
    };

    function deleteData(){
        setIsUploading(true);
        axios.delete(`${apiPath}${GET_GROUP_LIST_PATH}/${params.id}`,
        )
            .then((response) => {
                if (response.status === 204) {
                    notifyDeleteSuccess();
                    setIsWindowOpen(false);
                    navigate('/usergroupSearchview');
                }
                setIsUploading(false);

            })
            .catch(error => {
                console.log(error);
                setIsUploading(false);
                return false;
            });
    }
// ==============================|| DELETE WINDOW RELATED ||============================== //

    function updateGroupObject(groupData) {
        setEditedGroupData(groupData);
    }

    function updateGroupMember(groupMember){
        setGroupMember(groupMember.currentList);
        setDeletedUserList(groupMember.deletedList);
    }

    function updateUserAuthList(userAuthData){
        setUserAuthData(userAuthData.currentList);
        setDeletedAuthList(userAuthData.deletedList);
    }

    const submitData = () => {
        setUserConfirm(true);
        setIsCollectData(!isCollectData);
    }

    const handleCancelClick = () =>{
        navigate('/usergroupSearchview');
    }

    useEffect(() => {
        if(params.id > 0 ){
            axios.get(`${apiPath}${GET_GROUP_LIST_PATH}/${params.id}`)
                .then((response) => {
                    if (response.status === 200) {
                        setUserGroupData(response.data);
                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        }
        else{
            //new record case
            setUserGroupData(
                {
                    "authIds": [],
                    "data": {},
                    "userIds": []
                }
            );
            setIsNewRecord(true);
        }

    }, []);

    useEffect(() => {
        if (Object.keys(userGroupData).length > 0 && userGroupData !== undefined) {
            setOnReady(true);
        }
        else if(isNewRecord){
            setOnReady(true);
        }
    }, [userGroupData]);

    useEffect(() => {
        if(userConfirm && onReady){
            //avoid delete and add user at the same time
            let finalDeletedUserList = getDeletedRecordWithRefList(deletedUserList, getIdList(groupMember));
            setIsUploading(true);
            axios.post(`${apiPath}${UPDATE_GROUP_PATH}`,
                {
                    "id": parseInt(params.id) !== -1? parseInt(params.id) : null,
                    "name": editedGroupData.userGroupName.trim(),
                    "description": editedGroupData.description == null ? "" : editedGroupData.description.trim(),
                    "addUserIds": getIdList(groupMember),
                    "removeUserIds": finalDeletedUserList,
                    "addAuthIds": userAuthData,
                    "removeAuthIds": deletedAuthList,
                },
            )
                .then((response) => {
                    if (response.status === 200) {
                        notifySaveSuccess();
                        setIsUploading(false);
                        navigate('/usergroupSearchview');
                    }
                })
                .catch(error => {
                    console.log(error);
                    setIsUploading(false);
                    return false;
                });
        }
        setUserConfirm(false);
    }, [editedGroupData]);

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <Grid container rowSpacing={3} columnSpacing={1.5}>
                <ThemeProvider theme={LIONER_FORM_THEME}>
                <Grid item xs={12} sx={{mt:-1, mb: -2.25}}>
                    <Typography variant="h5">{isNewRecord? "Create User Group" : "Maintain User Group"}</Typography>
                </Grid>
                {/*col 1*/}
                <Grid item xs={12} md={12} lg={5}>
                    <Grid container>
                        <Grid item xs={12} md={12} lg={12}>
                            <UserGroupInfoCard
                                updateGroupObject={updateGroupObject}
                                userGroupData={userGroupData}
                                isCollectData={isCollectData}
                                isNewRecord={isNewRecord}
                                setUserConfirm={setUserConfirm}
                                setIsCollectData={setIsCollectData}
                            />
                        </Grid>

                        <Grid item xs={12} md={12} lg={12} sx={{mt:1.5}}>
                            <UserAddCard
                                updateGroupMember={updateGroupMember}
                                userGroupData={userGroupData}
                                isCollectData={isCollectData}
                                isNewRecord={isNewRecord}
                            />
                        </Grid>
                    </Grid>
                </Grid>
                {/*col 2*/}
                <Grid item xs={12} md={12} lg={7}>
                    <GroupAuthCard
                        updateUserAuthList={updateUserAuthList}
                        userGroupData={userGroupData}
                        isCollectData={isCollectData}
                        isNewRecord={isNewRecord}
                    />
                </Grid>

                {/*bottom button*/}
                <Grid item s={12} md={12} lg={12} alignItems={"end"} justifyContent="center" sx={{mt:{lg:-1.5}}}>
                    <ThemeProvider theme={LIONER_BUTTON_THEME}>
                        <Grid container maxWidth justifyContent="flex-start">
                            <Grid item sx={{mr: 1.5}}>
                                <Button
                                    variant="contained"
                                    type="submit"
                                    color="save"
                                    onClick={submitData}
                                >
                                    Save
                                </Button>
                            </Grid>

                            <Grid item sx={{ml: 1.5, mr: 1.5}}>
                                <Button
                                    variant="contained"
                                    type="submit"
                                    color="cancel"
                                    onClick={handleCancelClick}
                                >
                                    Cancel
                                </Button>
                            </Grid>

                            <Grid item sx={{ml:1.5, mr:1.5}}>
                                <Button
                                    variant="contained"
                                    color="delete"
                                    disabled={isNewRecord}
                                    onClick={handleDeleteClick}
                                >
                                    Delete
                                </Button>
                                <GeneralConfirmWindow
                                    isWindowOpen={isWindowOpen}
                                    title={"Attention"}
                                    //content={`Confirm to delete User Group "${userGroupData.data.name}" ?`}
                                    content={`Are you sure to delete this user group?`}
                                    onNormalClose={handleClose}
                                    onConfirmClose={deleteData}
                                />
                            </Grid>

                        </Grid>
                    </ThemeProvider>
                </Grid>
                </ThemeProvider>
            </Grid>
    );
};

export default UserMaintainPage;
