// 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 LoadingComponent from "../extra-pages/LoadingComponent";
import {
    CHECK_DIV_DUPLICATE,
    GET_DIVISION_LIST,
    UPDATE_DIVISION_PATH
} from "../../utils/ApiPathConst";
import DivisionInfoCard from "./DivisionInfoCard";
import SubDivisionTable from "./SubDivisionTable";
import 'react-toastify/dist/ReactToastify.css';
import {
    GeneralConfirmWindow, getListByFieldName, notifyDeleteError,
    notifyDeleteSuccess,
    notifySaveSuccess, trimListDataBeforePost,
} from "../../utils/CommonFunction";
import UploadContext from "../../components/UploadProvider";
import {ThemeProvider} from "@emotion/react";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
import Qs from "qs";
import MainCard from "../../components/MainCard";

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

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


const DivisionEditPage = () => {
    const navigate = useNavigate();
    const params = useParams();
    const [onReady, setOnReady] = useState(false);
    const [isCollectData, setIsCollectData] = useState(false);
    const [editedDivisionData, setEditedDivisionData] = useState({});
    const [divisionData, setDivisionData] = useState({});
    const [subDivisionList, setSubDivisionList] = useState([]);
    const [deletedList, setDeletedList] = React.useState([]);
    const [userConfirm, setUserConfirm] = useState(false);
    const [isNewRecord, setIsNewRecord] = useState(false);
    const { setIsUploading } = useContext(UploadContext);
    const [validToSave, setValidToSave] = useState(true);
// ==============================|| 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_DIVISION_LIST}/${params.id}`,
        )
            .then((response) => {
                if (response.status === 200) {
                    notifyDeleteSuccess();
                    setIsWindowOpen(false);
                    setIsUploading(false);
                    navigate('/division');
                }
            })
            .catch(error => {
                console.log(error);
                setIsUploading(false);
                return false;
            });
    }
// ==============================|| DELETE WINDOW RELATED ||============================== //

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

    function updateSubDivisionList(tableData, isAllSaved) {
        if(isCollectData){
            if(isAllSaved){
                setSubDivisionList(trimListDataBeforePost(tableData.records));
                setDeletedList(tableData.deletedList);
                setValidToSave(true);
            }
            else{
                notifyDeleteError("Please save all sub-division name before saving division!");
                setIsCollectData(false);
                setValidToSave(false);
            }
        }
    }

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

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

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

    }, []);

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

    useEffect(() => {
        if (userConfirm && validToSave) {
            const tempList = getListByFieldName(subDivisionList, 'name');


            const duplicates = tempList.filter((value, index) => {
                return tempList.lastIndexOf(value) !== index;
            });

            if(duplicates.length === 0){
                axios.get(`${apiPath}${CHECK_DIV_DUPLICATE}`,
                    {
                        params: {
                            "divisionId": params.id,
                            "division": editedDivisionData.divisionName,
                            "subDivisionList": getListByFieldName(subDivisionList,'name') === null ? " " : getListByFieldName(subDivisionList,'name')
                        },
                        paramsSerializer: function (params) {
                            return Qs.stringify(params, { arrayFormat: 'repeat' });
                        },
                    })
                    .then((response) => {
                        if (response.status === 200) {
                            if (!response.data.valid) {
                                let temp = "";
                                if(response.data.duplicatedDivision.length >0){
                                    temp += response.data.duplicatedDivision;
                                }

                                if(response.data.duplicatedSubDivision.length >0){
                                    if(temp.length >0){
                                        temp += "," + response.data.duplicatedSubDivision;
                                    }
                                    else{
                                        temp = response.data.duplicatedSubDivision;
                                    }
                                }
                                notifyDeleteError(`${temp} already exists.`)
                            } else if (response.data.valid) {
                                processUpload();
                            }
                            setUserConfirm(false);
                            setIsCollectData(false);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        return true;
                    });
            }
            else{
                notifyDeleteError(`${duplicates.toString()} have duplicated record.`)
                setUserConfirm(false);
                setIsCollectData(false);
            }

        }
    }, [editedDivisionData,validToSave]);

    function processUpload(){
            setIsUploading(true);
            axios.post(`${apiPath}${UPDATE_DIVISION_PATH}`,
                {
                    "id": parseInt(params.id),
                    "name": editedDivisionData.divisionName.trim(),
                    "branch": editedDivisionData.branch,
                    "subDivisionList": subDivisionList,
                    "subDivisionDeleteList": deletedList,
                },
            )
                .then((response) => {
                    if (response.status === 200) {
                        notifySaveSuccess();
                        setIsUploading(false);
                        navigate('/division');
                    }
                })
                .catch(error => {
                    console.log(error);
                    setIsUploading(false);
                    return false;
                });
        setUserConfirm(false);
    }

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <Grid item sx={{height: "100%", width: "100%", flexGrow: 1}}>
                <Grid container alignItems="stretch" rowSpacing={3} columnSpacing={2.5}>
                    <ThemeProvider theme={LIONER_FORM_THEME}>
                    <Grid item xs={12} sx={{mt:-1, mb: -2.25}}>
                        <Typography variant="h5">{isNewRecord? "Create Division" : "Maintain Division"}</Typography>
                    </Grid>
                    {/*col 1*/}
                    <Grid item xs={12} md={12} lg={12}>
                        <DivisionInfoCard
                            updateGroupObject={updateGroupObject}
                            divisionData={divisionData.data}
                            isCollectData={isCollectData}
                            isNewRecord={isNewRecord}
                            setUserConfirm={setUserConfirm}
                            setIsCollectData={setIsCollectData}
                        />
                    </Grid>
                    {/*col 2*/}
                    <Grid item alignItems="stretch" xs={12} md={12} lg={12} sx={{mt:{lg:-1.5}}}>
                        <MainCard sx={{mb:3, width:CARD_MAX_WIDTH}} contentSX={{mt:-2, ml:-1.5, mr:-1.5,mb:-1}}>
                            <div style={{/*height: '62vh',*/ width: '100%'}}>
                                <SubDivisionTable
                                    updateSubDivisionList={updateSubDivisionList}
                                    divisionData={divisionData.subDivision}
                                    setIsCollectData={setIsCollectData}
                                    isCollectData={isCollectData}
                                    isNewRecord={isNewRecord}
                                />
                            </div>
                        </MainCard>
                    </Grid>

                    {/*bottom button*/}
                    <Grid container maxWidth justifyContent="flex-start" sx={{mt:{lg:-1.5}}}>
                        <Grid item>
                            <ThemeProvider theme={LIONER_BUTTON_THEME}>
                                <Grid container>
                                    <Grid item sx={{ml:3, 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"
                                            disabled={isNewRecord}
                                            onClick={handleCancelClick}
                                        >
                                            Cancel
                                        </Button>
                                    </Grid>

                                    <Grid item sx={{ml:1.5, mr:3, }}>
                                        <Button
                                            variant="contained"
                                            color="delete"
                                            disabled={isNewRecord}
                                            onClick={handleDeleteClick}
                                        >
                                            Delete
                                        </Button>
                                    </Grid>
                                    <GeneralConfirmWindow
                                        isWindowOpen={isWindowOpen}
                                        title={"Attention"}
                                        //content={`Confirm to delete Division "${divisionData.data.name}" ?`}
                                        content={`Are you sure to delete this division?`}
                                        onNormalClose={handleClose}
                                        onConfirmClose={deleteData}
                                    />
                                </Grid>
                            </ThemeProvider>
                        </Grid>
                    </Grid>
                    </ThemeProvider>
                </Grid>
            </Grid>
    );
};

export default DivisionEditPage;
