// material-ui
import {
    Button,
    Grid,
    Typography,
    Stack,
    Box,
    Tab
} from '@mui/material';
import { TabPanel, TabContext, TabList } from '@mui/lab';
import MainCard from "components/MainCard";

import { useEffect, useState, lazy } from "react";
import axios from "axios";
import { useNavigate, useParams } from "react-router-dom";
import { GLD_USER_PATH, DELETE_USER, POST_ADMIN_USER_REGISTER } from "utils/ApiPathConst";
import {isGrantedAny} from "auth/utils";
import Loadable from 'components/Loadable';
const UserInformationCard = Loadable(lazy(() => import('./UserInformationCard')));
const LoadingComponent = Loadable(lazy(() => import('../../extra-pages/LoadingComponent')));
const UserGroupCard = Loadable(lazy(() => import('./UserGroupCard')));
const UserAuthorityCard = Loadable(lazy(() => import('./UserAuthorityCard')));
const LoginGrid = Loadable(lazy(() => import('./LoginGrid')));
import { ThemeProvider } from "@emotion/react";
import { PNSPS_BUTTON_THEME } from "themes/buttonConst";

import {
    GeneralConfirmWindow,
    getDeletedRecordWithRefList,
    notifyDeleteSuccess,
    notifySaveSuccess,
} from "utils/CommonFunction";
import ForwardIcon from '@mui/icons-material/Forward';
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import { useIntl } from 'react-intl';

const BackgroundHead = {
    backgroundImage: `url(${titleBackgroundImg})`,
    width: '100%',
    height: '100%',
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
    backgroundColor: '#0C489E',
    backgroundPosition: 'right'
}
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const UserMaintainPage = () => {
    const intl = useIntl();
    const params = useParams();
    const navigate = useNavigate();
    const [userData, setUserData] = useState({});
    const [onReady, setOnReady] = useState(false);
    const [isCollectData, setIsCollectData] = useState(false);
    const [editedCustomerData, setEditedCustomerData] = useState({});
    const [userGroupData, setUserGroupData] = useState([]);
    const [userAuthData, setUserAuthData] = useState([]);
    const [userConfirm, setUserConfirm] = useState(false);
    const [isNewRecord, setIsNewRecord] = useState(false);
    const [refUserData, setRefUserData] = useState({});
    const [editMode, setEditMode] = useState(false);
    const [createMode, setCreateMode] = useState(false);
    const [selectedTab, setSelectedTab] = useState("1");

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

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

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

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

    const handleChange = (event, newValue) => {
        setSelectedTab(newValue);
    }

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

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

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

    useEffect(() => {
        if (params.id > 0) {
            loadData()
        }
        else {
            setUserData(
                {
                    "authIds": [],
                    "data": {},
                    "groupIds": []
                }
            );
            setRefUserData(
                {
                    "authIds": [],
                    "data": {},
                    "groupIds": []
                }
            );
            setIsNewRecord(true);
            setCreateMode(true)
        }

    }, []);

    const loadData = () => {
        setOnReady(false);
        setEditMode(false);
        axios.get(`${GLD_USER_PATH}/${params.id}`)
            .then((response) => {
                if (response.status === 200) {
                    setRefUserData(response.data);
                    setUserData(response.data);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        // if (Object.keys(userData).length > 0 && userData !== undefined) {
        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);
            // console.log(userGroupData)
            // console.log(userAuthData)
            if (parseInt(params.id) > -1) {
                axios.post(`${GLD_USER_PATH}/${params.id}`,
                    {
                        "enName": editedCustomerData.enName,
                        "locked": editedCustomerData.locked,
                        // "password": editedCustomerData.password,
                        // "phone": editedCustomerData.phone,
                        "post": editedCustomerData.post,
                        "emailAddress": editedCustomerData.emailAddress,
                        "addGroupIds": userGroupData,
                        "removeGroupIds": deletedUserGroup,
                        "addAuthIds": userAuthData,
                        "removeAuthIds": deletedUserAuth,
                    },
                ).then((response) => {
                    if (response.status === 204) {
                        notifySaveSuccess();
                        location.reload();
                    }
                })
                    .catch(error => {
                        console.log(error);
                        return false;
                    });
            } else {
                if (editedCustomerData.pwErr) return;
                axios.post(POST_ADMIN_USER_REGISTER,
                    {
                        "username": editedCustomerData.username,
                        "name": editedCustomerData.username,
                        "password": editedCustomerData.password,
                        "enName": editedCustomerData.enName,
                        "locked": editedCustomerData.locked,
                        "emailAddress": editedCustomerData.emailAddress,
                        "post": editedCustomerData.post,
                        "addGroupIds": userGroupData,
                        "removeGroupIds": [],
                        "addAuthIds": userAuthData,
                        "removeAuthIds": [],
                    },
                ).then((response) => {
                    if (response.status === 200) {
                        notifySaveSuccess();
                        navigate('/userSearchview');
                    }
                })
                .catch(function (error){
                    // console.log(error.response.data)
                    if(error.response.data.error == "USERNAME_NOT_AVAILABLE"){
                        alert("Username is already used.")
                    }
                    return false;
                });
        }
        }
        setUserConfirm(false);
    }, [editedCustomerData, userGroupData, userAuthData]);

    const onEditClick = () => {
        setEditMode(true);
    };

    return (
        !onReady ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            <Grid container sx={{ minHeight: '87vh', backgroundColor: 'backgroundColor.default' }}>
                <Grid item xs={12}>
                    <div style={BackgroundHead}>
                        <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                            <Typography ml={15} color='#FFF' variant="h4" sx={{ "textShadow": "0px 0px 25px #0C489E" }}>{isNewRecord ? "Create GLD User" : "Maintain GLD User"}</Typography>
                        </Stack>
                    </div>
                </Grid>
                <Grid item xs={12}>
                    <Button title="Back" sx={{ ml: 3.5, mt: 2 }} style={{ border: '2px solid' }} variant="outlined" onClick={() => { navigate("/userSearchview") }}>
                        <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
                    </Button>
                </Grid>
                {/*col 1*/}
                {/*bottom button*/}

                {
                    isGrantedAny(["MAINTAIN_USER", "MAINTAIN_GLD_USER"]) ?
                        <Grid item s={12} md={12} lg={12} sx={{ mt: 2, mb: 2 }} alignItems={"start"} justifyContent="center">
                            <Grid container maxWidth justifyContent="flex-start">
                                {
                                    createMode?
                                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                            <Grid item sx={{ ml: 3, mr: 3 }}>
                                                <Button
                                                    size="large"
                                                    variant="contained"
                                                    type="submit"
                                                    sx={{
                                                        textTransform: 'capitalize',
                                                        alignItems: 'end'
                                                    }}
                                                    onClick={submitData}
                                                >
                                                    Create User
                                                </Button>
                                            </Grid>
                                        </ThemeProvider>
                                    :
                                        editMode ?
                                            <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                <Grid item sx={{ ml: 3, mr: 3 }}>
                                                    <Button
                                                        variant="contained"
                                                        onClick={loadData}
                                                        color="cancel"
                                                    >
                                                        Reset & Back
                                                    </Button>
                                                </Grid>
                                                <Grid item sx={{ ml: 3, mr: 3 }}>
                                                    <Button
                                                        size="large"
                                                        variant="contained"
                                                        type="submit"
                                                        sx={{
                                                            textTransform: 'capitalize',
                                                            alignItems: 'end'
                                                        }}
                                                        onClick={submitData}
                                                    >
                                                        Save
                                                    </Button>
                                                </Grid>
                                            </ThemeProvider> 
                                        :
                                            <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                                                <Grid item sx={{ ml: 3, mr: 3 }}>
                                                    <Button
                                                        variant="contained"
                                                        onClick={onEditClick}
                                                    >
                                                        Edit
                                                    </Button>
                                                </Grid>
                                                <Grid item sx={{ ml: 3, mr: 3 }}>
                                                    <Button
                                                        size="large"
                                                        variant="contained"
                                                        sx={{
                                                            textTransform: 'capitalize',
                                                            alignItems: 'end'
                                                        }}
                                                        disabled={isNewRecord}
                                                        onClick={handleDeleteClick}
                                                        color='error'
                                                    >
                                                        Delete User
                                                    </Button>
                                                    <GeneralConfirmWindow
                                                        isWindowOpen={isWindowOpen}
                                                        title={"Attention"}
                                                        content={`Confirm to delete User "${userData.data.username}" ?`}
                                                        onNormalClose={handleClose}
                                                        onConfirmClose={deleteData}
                                                    />
                                                </Grid>
                                            </ThemeProvider>                                
                                }
                            </Grid>
                        </Grid>
                        : <></>
                }

                <Grid item xs={12} md={5} lg={5}>
                    <Grid container>
                        <Grid item xs={12} md={12} lg={12}>
                            <Box xs={12} ml={4} mt={2} sx={{ borderRadius: '10px', backgroundColor: '#fff' }}>
                                <UserInformationCard
                                    updateUserObject={updateUserObject}
                                    userData={userData}
                                    isCollectData={isCollectData}
                                    isNewRecord={isNewRecord}
                                    editMode={editMode}
                                    createMode={createMode}
                                />
                            </Box>
                        </Grid>

                        <Grid item xs={12} md={12} lg={12} sx={{ mt: 0.5 }}>
                            <Box xs={12} ml={4} mt={2} sx={{ borderRadius: '10px', backgroundColor: '#fff' }}>
                                <UserGroupCard
                                    updateUserGroupList={updateUserGroupList}
                                    userData={userData}
                                    isCollectData={isCollectData}
                                    isNewRecord={isNewRecord}
                                    editMode={editMode}
                                    createMode={createMode}
                                />
                            </Box>
                        </Grid>
                    </Grid>
                </Grid>
                {/*col 2*/}
                <Grid item xs={12} md={7} lg={7}>
                    <Box xs={12} ml={2} mt={2} mr={3} sx={{ borderRadius: '10px', backgroundColor: '#fff' }}>
                        <UserAuthorityCard
                            updateUserAuthList={updateUserAuthList}
                            userData={userData}
                            isCollectData={isCollectData}
                            isNewRecord={isNewRecord}
                            editMode={editMode}
                            createMode={createMode}
                        />
                    </Box>
                </Grid>
                <Grid item xs={12} md={12} lg={12}>
                    <Box xs={12} ml={2} mt={2} mr={3} sx={{ borderRadius: '10px', backgroundColor: '#fff' }}>
                        <MainCard elevation={0} border={false} content={false} sx={{maxWidth: '100%', mr:2, width: "-webkit-fill-available"}}>
                            <TabContext value={selectedTab}>
                                <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                                    <TabList  variant="scrollable" onChange={handleChange} aria-label={intl.formatMessage({ id: 'ariaRelatedRecords' })}>
                                        <Tab label="Login Log" value="1" />
                                    </TabList>
                                </Box>
                                <TabPanel value="1">
                                    <LoginGrid
                                        u1 = {params.id}
                                    />
                                </TabPanel>
                            </TabContext>
                        </MainCard>
                    </Box>
                </Grid>
            </Grid>
    );
};

export default UserMaintainPage;
