// 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 {useNavigate, useParams} from "react-router-dom";
import UserInformationCard from "./UserInformationCard";
import LoadingComponent from "../extra-pages/LoadingComponent";
import UserGroupCard from "./UserGroupCard";
import UserAuthorityCard from "./UserAuthorityCard";
import {CREATE_USER_PATH, GET_USER_PATH} from "../../utils/ApiPathConst";
import {
    GeneralConfirmWindow,
    getDeletedRecordWithRefList,
    notifyDeleteSuccess,
    notifySaveSuccess
} from "../../utils/CommonFunction";
import UploadContext from "../../components/UploadProvider";
import {ThemeProvider} from "@emotion/react";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";

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

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


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

    const params = useParams();
    const navigate = useNavigate();
    const [refUserData, setRefUserData] = React.useState({});
    const [userData, setUserData] = React.useState({});
    const [onReady, setOnReady] = useState(false);
    const [isCollectData, setIsCollectData] = useState(false);
    const [editedUserData, setEditedUserData] = useState({});
    const [userGroupData,setUserGroupData] = useState([]);
    const [userAuthData,setUserAuthData] = useState([]);
    const [userConfirm, setUserConfirm] = useState(false);
    const [isNewRecord, setIsNewRecord] = useState(false);
    const [requestError, setRequestError] = useState({});

    function updateUserObject(userData) {
        setEditedUserData(userData);
    }

    function updateUserGroupList(userGroupData){
        setUserGroupData(userGroupData);
    }

    function updateUserAuthList(userAuthData){
        setUserAuthData(userAuthData);
    }

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

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

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

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

    function deleteData(){
        setIsUploading(true);
        axios.delete(`${apiPath}${GET_USER_PATH}/${params.id}`,
        )
            .then((response) => {
                if (response.status === 204) {
                    notifyDeleteSuccess();
                    setIsWindowOpen(false);
                    setIsUploading(false);
                    navigate('/userSearchview');
                }
            })
            .catch(error => {
                console.log(error);
                setIsUploading(false);
                return false;
            });
    }
// ==============================|| DELETE WINDOW RELATED ||============================== //

    useEffect(() => {
        if(params.id > 0){
            axios.get(`${apiPath}${GET_USER_PATH}/${params.id}`)
                .then((response) => {
                    if (response.status === 200) {
                        setUserData(response.data);
                        setRefUserData(response.data);
                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        }
        else{
            setUserData(
                {
                    "authIds": [],
                    "data": {},
                    "groupIds": []
                }
            );
            setRefUserData(
                {
                    "authIds": [],
                    "data": {},
                    "groupIds": []
                }
            );
            setIsNewRecord(true);
        }

    }, []);

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

    useEffect(() => {
        if(userConfirm && onReady){
            const deletedUserAuth = getDeletedRecordWithRefList(refUserData.authIds,userAuthData);
            const deletedUserGroup = getDeletedRecordWithRefList(refUserData.groupIds,userGroupData);
            setIsUploading(true);
            axios.post(`${apiPath}${CREATE_USER_PATH}`,
                {
                    "id": parseInt(params.id),
                    "fullname": editedUserData.fullname.trim(),
                    "name": editedUserData.username.trim(),
                    "locked": editedUserData.locked,
                    "username": editedUserData.username.trim(),
                    "phone1": editedUserData.phone1 === null ? "" : editedUserData.phone1.trim(),
                    // "post": editedUserData.post === null ? "" : editedUserData.post.trim(),
                    "email": editedUserData.email === null ? "": editedUserData.email.trim(),
                    "userGroupId": editedUserData.userGroupId ?? null,
                    "password": editedUserData.password ?? null,
                    "twoFactorEnabled": editedUserData.twoFactorEnabled ?? false,
                    "consultantIds": editedUserData.consultantIds ?? [],
                    // "addGroupIds": userGroupData,
                    // "removeGroupIds": deletedUserGroup,
                    // "addAuthIds": userAuthData,
                    // "removeAuthIds": deletedUserAuth,
                },
            ).then((response) => {
                if (response.status === 200) {
                    notifySaveSuccess();
                    setIsUploading(false);
                    navigate('/userSearchview');
                }

            })
                .catch(error => {
                    setIsUploading(false);
                    if (error.response.status === 422){
                        //password error
                        const formErrors = {};
                        if(error.response.data.error === "Incorrect existing password"){
                            formErrors.password = error.response.data.error;
                        }
                        else{
                            formErrors.password = error.response.data.error;
                        }
                        setRequestError(formErrors);
                    }
                    console.log(error);
                    return false;
                });
        }
        setUserConfirm(false);
        setIsCollectData(false);
    }, [editedUserData]);

    return (
        !onReady || userData?.groupId==3 ?
            <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="h4">{isNewRecord? "Create User" : "Maintain User"}</Typography>
                </Grid>
                {/*col 1*/}
                <Grid item xs={12} md={12}/* lg={5}*/>
                    <UserInformationCard
                        updateUserObject={updateUserObject}
                        userData={userData}
                        setUserData={setUserData}
                        isCollectData={isCollectData}
                        isNewRecord={isNewRecord}
                        setUserConfirm={setUserConfirm}
                        setIsCollectData={setIsCollectData}
                        requestError={requestError}
                    />
                </Grid>
                {/*col 2*/}
                {/*<Grid item xs={12} md={12} lg={7}>
                    <Grid container>
                        <Grid item xs={12} md={12} lg={12} >
                            <UserGroupCard
                                updateUserGroupList={updateUserGroupList}
                                userData={userData}
                                isCollectData={isCollectData}
                                isNewRecord={isNewRecord}
                            />
                        </Grid>
                        <Grid item xs={12} md={12} lg={12} sx={{mt: {xs:3, md:3 ,lg:1.5}}}>
                            <UserAuthorityCard
                                updateUserAuthList={updateUserAuthList}
                                userData={userData}
                                isCollectData={isCollectData}
                                isNewRecord={isNewRecord}
                            />
                        </Grid>


                    </Grid>

                </Grid>*/}

                {/*bottom button*/}
                <Grid item s={12} md={12} lg={12} sx={{mt:-1.5}} alignItems={"end"} justifyContent="center">
                    <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"
                                    color="cancel"
                                    onClick={handleCancelClick}
                                >
                                    Cancel
                                </Button>
                            </Grid>
                            {!isNewRecord && (
                                <Grid item sx={{ml:{xs:1.5, md:1.5, lg:1.5}, mr:1.5}}>
                                    <Button
                                        variant="contained"
                                        color="delete"
                                        onClick={handleDeleteClick}
                                    >
                                        Delete
                                    </Button>
                                    <GeneralConfirmWindow
                                        isWindowOpen={isWindowOpen}
                                        title={"Attention"}
                                        //content={`Confirm to delete User "${userData.data.username}" ?`}
                                        content={"Are you sure to delete this user?"}
                                        onNormalClose={handleClose}
                                        onConfirmClose={deleteData}
                                    />
                                </Grid>
                            )}

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

export default UserMaintainPage;
