// material-ui
import {
    Button,
    Grid, Typography, Stack, Box
} from '@mui/material';
import { useEffect, useState, useRef, lazy } from "react";
import axios from "axios";
import { useParams } from "react-router-dom";
import {
    GeneralConfirmWindow,
    getDeletedRecordWithRefList,
    getIdList,
    notifyActionError,
    notifyDeleteSuccess,
    notifySaveSuccess
} from "../../utils/CommonFunction";
import { POST_AND_UPDATE_USER_GROUP, GET_GROUP_LIST_PATH } from "utils/ApiPathConst";

import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(lazy(() => import('../extra-pages/LoadingComponent')));
const GroupAuthCard = Loadable(lazy(() => import('./GroupAuthCard')));
const UserGroupInfoCard = Loadable(lazy(() => import('./UserGroupInfoCard')));
const UserAddCard = Loadable(lazy(() => import('./UserAddCard')));
import { useNavigate } from "react-router";
import ForwardIcon from '@mui/icons-material/Forward';
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import { isGrantedAny } from "auth/utils";

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

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


const UserMaintainPage = () => {
    const params = useParams();
    const navigate = useNavigate();
    const [onReady, setOnReady] = useState(false);
    const [editMode, setEditMode] = useState(false);
    const [isCollectData, setIsCollectData] = useState(false);
    const [editedGroupData, setEditedGroupData] = useState({});
    const [userGroupData, setUserGroupData] = useState([]);
    const [userAuthData, setUserAuthData] = useState([]);
    const saveInProgressRef = useRef(false);
    const [groupMember, setGroupMember] = useState([]);
    const [isNewRecord, setIsNewRecord] = useState(false);
    const [deletedUserList, setDeletedUserList] = useState([]);
    const [deletedAuthList, setDeletedAuthList] = useState([]);

    const [isWindowOpen, setIsWindowOpen] = useState(false);
    const handleClose = () => {
        setIsWindowOpen(false);
    };

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

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

    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 = async () => {
        if (!onReady || saveInProgressRef.current) {
            return;
        }
        saveInProgressRef.current = true;
        setIsCollectData(!isCollectData);

        try {
            const isNameValid = await validateGroupName();
            if (!isNameValid) {
                return;
            }
            const latestGroupFormData = getLatestGroupFormData();
            const finalDeletedUserList = getDeletedRecordWithRefList(deletedUserList, getIdList(groupMember));
            const response = await axios.post(POST_AND_UPDATE_USER_GROUP, {
                id: parseInt(params.id) !== -1 ? parseInt(params.id) : null,
                name: latestGroupFormData.userGroupName,
                description: latestGroupFormData.description,
                addUserIds: getIdList(groupMember),
                removeUserIds: finalDeletedUserList,
                addAuthIds: userAuthData,
                removeAuthIds: deletedAuthList,
            });
            if (response.status === 200) {
                navigate('/usergroupSearchview');
                notifySaveSuccess();
            }
        } catch (error) {
            console.log(error);
            notifyActionError(error?.response?.data?.message || "Save failed.");
        } finally {
            saveInProgressRef.current = false;
        }
    };

    const normalizeName = (name) => (name || "").trim().toLowerCase();

    const getLatestGroupFormData = () => {
        const nameEl = document.getElementById("groupName");
        const descEl = document.getElementById("description");
        // Prefer what the user actually typed. Parent `editedGroupData` can still be stale on the
        // first Save click (sync runs after `isCollectData` toggles in a child effect).
        return {
            userGroupName: nameEl != null ? nameEl.value : (editedGroupData?.userGroupName ?? ""),
            description: descEl != null ? descEl.value : (editedGroupData?.description ?? "")
        };
    };

    const validateGroupName = async () => {
        const latestGroupFormData = getLatestGroupFormData();
        const groupName = (latestGroupFormData.userGroupName || "").trim();
        if (groupName.length === 0) {
            notifyActionError("User Group Name is required.");
            return false;
        }

        try {
            const response = await axios.get(GET_GROUP_LIST_PATH, {
                params: {
                    name: groupName,
                    start: 0,
                    limit: 1000
                }
            });
            const records = response?.data?.records || [];
            const currentId = parseInt(params.id);
            const isDuplicateName = records.some((record) =>
                normalizeName(record?.name) === normalizeName(groupName) &&
                parseInt(record?.id) !== currentId
            );

            if (isDuplicateName) {
                notifyActionError(`User Group Name "${groupName}" already exists.`);
                return false;
            }
        } catch (error) {
            console.log(error);
            notifyActionError("Unable to validate User Group Name. Please try again.");
            return false;
        }

        return true;
    };

    useEffect(() => {
        if (params.id > 0) {
            axios.get(`${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);
            setEditMode(true);
        }

    }, []);

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

    return (
        !onReady ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            <Grid container sx={{ 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 User Group" : "Maintain User Group"}</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("/usergroupSearchview") }}>
                        <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
                    </Button>
                </Grid>

                {/*top button*/}
                {
                    isGrantedAny("MAINTAIN_GROUP")?
                    <Grid item s={12} md={12} lg={12} alignItems={"start"} justifyContent="center">
                    <Grid container maxWidth justifyContent="flex-start" sx={{ mt: 1 }}>
                        {editMode ?
                            <>
                                <Grid item sx={{ ml: 3, mr: 3 }}>
                                    <Button
                                        size="large"
                                        variant="contained"
                                        type="submit"
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end'
                                        }}
                                        onClick={() => { location.reload() }}
                                        color="secondary"
                                    >
                                        <Typography variant="h5">Reset & Back</Typography>
                                    </Button>
                                </Grid>

                                <Grid item sx={{ ml: 3, mr: 3 }}>
                                    <Button
                                        size="large"
                                        variant="contained"
                                        type="submit"
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end'
                                        }}
                                        onClick={submitData}
                                    >
                                        <Typography variant="h5">Save</Typography>
                                    </Button>
                                </Grid>
                            </>

                            :
                            <>
                                <Grid item sx={{ ml: 3, mr: 3 }}>
                                    <Button
                                        size="large"
                                        variant="contained"
                                        type="submit"
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end'
                                        }}
                                        onClick={() => { setEditMode(true) }}
                                    >
                                        <Typography variant="h5">Edit</Typography>
                                    </Button>
                                </Grid>

                                <Grid item sx={{ ml: 3, mr: 3 }}>
                                    <Button
                                        size="large"
                                        variant="contained"
                                        sx={{
                                            textTransform: 'capitalize',
                                            alignItems: 'end'
                                        }}
                                        color="error"
                                        disabled={isNewRecord}
                                        onClick={handleDeleteClick}
                                    >
                                        <Typography variant="h5">Delete User Group</Typography>
                                    </Button>
                                    <GeneralConfirmWindow
                                        isWindowOpen={isWindowOpen}
                                        title={"Attention"}
                                        content={`Confirm to delete User Group "${userGroupData.data.name}" ?`}
                                        onNormalClose={handleClose}
                                        onConfirmClose={deleteData}
                                    />
                                </Grid>

                            </>
                        }

                    </Grid>
                </Grid>
                :<></>
                }



                {/*col 1*/}
                <Grid item xs={12} md={5} lg={5}>
                    <Grid container>
                        <Grid item xs={12} md={12} lg={12}>
                            <Box xs={12} ml={0} mt={-1} mr={0} sx={{ p: 1, borderRadius: '10px' }}>
                                <UserGroupInfoCard
                                    updateGroupObject={updateGroupObject}
                                    userGroupData={userGroupData}
                                    isCollectData={isCollectData}
                                    isNewRecord={isNewRecord}
                                    editMode={editMode}
                                />
                            </Box>
                        </Grid>

                        <Grid item xs={12} md={12} lg={12} sx={{ mt: 3 }}>
                            <Box xs={12} ml={0} mt={-5} mr={0} sx={{ p: 1, borderRadius: '10px' }}>
                                <UserAddCard
                                    updateGroupMember={updateGroupMember}
                                    userGroupData={userGroupData}
                                    isCollectData={isCollectData}
                                    isNewRecord={isNewRecord}
                                    editMode={editMode}
                                />
                            </Box>
                        </Grid>
                    </Grid>
                </Grid>
                {/*col 2*/}
                <Grid item xs={12} md={7} lg={7}>
                    <Box xs={12} ml={-2} mt={-1} mr={0} sx={{ p: 1, borderRadius: '10px' }}>
                        <GroupAuthCard
                            updateUserAuthList={updateUserAuthList}
                            userGroupData={userGroupData}
                            isCollectData={isCollectData}
                            isNewRecord={isNewRecord}
                            editMode={editMode}
                        />
                    </Box>
                </Grid>
            </Grid>
    );
};

export default UserMaintainPage;
