// material-ui
import {
    Button,
    CardContent, Divider, FormControlLabel,
    Grid, InputAdornment, Switch, TextField, Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useForm} from "react-hook-form";
import {useEffect, useState} from "react";
import * as React from "react";
import {LIONER_BUTTON_THEME, GENERAL_RED_COLOR} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {GET_PASSWORD_POLICY_PATH, UPDATE_SETTING_PATH} from "../../utils/ApiPathConst";
import LoadingComponent from "../extra-pages/LoadingComponent";
import {getObjectByName, notifySaveSuccess} from "../../utils/CommonFunction";
import {SETTING_STRING_DICT} from "../../utils/SettingConst";

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

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

const PasswordPolicyPage = () => {

    const { reset, register, handleSubmit } = useForm()
    const [aNonA, setANonA] = useState(false);
    const [needSpecialCharacter, setNeedSpecialCharacter] = useState(false);
    const [noUsernameAsPart, setNoUsernameAsPart] = useState(false);
    const [noConsecutiveChar, setNoConsecutiveChar] = useState(false);
    const [onReady, setOnReady] = useState(false);
    const [errors, setErrors] = useState({});

    const onSubmit = (data) => {

        const formErrors = {};
        if (!data.passwordLength) {
            formErrors.passwordLength = 'Setting value cannot be null';
        }

        if (!data.passwordDuration) {
            formErrors.passwordDuration = 'Setting value cannot be null';
        }

        if (!data.passwordHistory) {
            formErrors.passwordHistory = 'Setting value cannot be null';
        }

        if (!data.maxLoginFailure) {
            formErrors.maxLoginFailure = 'Setting value cannot be null';
        }

        if (!data.loginFailPenaltyTime) {
            formErrors.loginFailPenaltyTime = 'Setting value cannot be null';
        }

        setErrors(formErrors);

        if (Object.keys(formErrors).length === 0) {
            let tempSettingList =[];
            tempSettingList.push({
                "name": SETTING_STRING_DICT.PASSWORD_LENGTH,
                "value": data.passwordLength
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.PASSWORD_DURATION,
                "value": data.passwordDuration
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.PASSWORD_HISTORY,
                "value": data.passwordHistory
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.LOGIN_ATTEMPT_LIMIT,
                "value": data.maxLoginFailure
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.LOGIN_ATTEMPT_PENALTY,
                "value": data.loginFailPenaltyTime
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.PASSWORD_RULE_NUMBER_AND_CHAR,
                "value": aNonA.toString()
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.PASSWORD_RULE_SPECIAL_CHAR,
                "value": needSpecialCharacter.toString()
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.PASSWORD_RULE_NO_USERNAME,
                "value": noUsernameAsPart.toString()
            });
            tempSettingList.push({
                "name": SETTING_STRING_DICT.PASSWORD_RULE_NO_THREE_CONSECUTIVE_CHAR,
                "value": noConsecutiveChar.toString()
            });

            axios.put(`${apiPath}${UPDATE_SETTING_PATH}`,
                {
                    settingList: tempSettingList
                },
            )
                .then((response) => {
                    if (response.status === 204) {
                        notifySaveSuccess();
                    }
                })
                .catch(error => {
                    console.log(error);
                    return false;
                });
        }
    };

    const [refRecord, setRefRecord] = useState([]);

    useEffect(() => {
        getSettingList();
    }, []);

    useEffect(() => {
        if(refRecord.length >0){
            setANonA(getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_RULE_NUMBER_AND_CHAR).value === "true")
            setNeedSpecialCharacter(getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_RULE_SPECIAL_CHAR).value === "true")
            setNoConsecutiveChar(getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_RULE_NO_USERNAME).value === "true");
            setNoUsernameAsPart(getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_RULE_NO_THREE_CONSECUTIVE_CHAR).value === "true");
            setOnReady(true);
        }
    }, [refRecord]);

    function getSettingList() {
        axios.get(`${apiPath}${GET_PASSWORD_POLICY_PATH}`
        )
            .then((response) => {
                if (response.status === 200) {
                    setRefRecord(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function resetForm(){
        setANonA(getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_RULE_NUMBER_AND_CHAR).value === "true")
        setNeedSpecialCharacter(getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_RULE_SPECIAL_CHAR).value === "true")
        setNoConsecutiveChar(getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_RULE_NO_USERNAME).value === "true");
        setNoUsernameAsPart(getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_RULE_NO_THREE_CONSECUTIVE_CHAR).value === "true");
        reset();
    }
    return (
        !onReady ?
            <LoadingComponent/>
            :
        <Grid container rowSpacing={4.5} columnSpacing={2.75} justifyContent="center">
            <ThemeProvider theme={LIONER_FORM_THEME}>
            <Grid item xs={12} sx={{mb: -2.25}}>
                <Typography variant="h4">Password Policy</Typography>
            </Grid>
            <Grid item xs={12} md={11} lg={10} >
                <MainCard xs={12} md={12} lg={12}
                          border={false}
                          content={false}>

                    <form onSubmit={handleSubmit(onSubmit)}>
                        {/*Title*/}
                        <CardContent sx={{ px: 2.5, pt: 2 }}>
                        </CardContent>

                        <Grid container alignItems={"center"} justifyContent="center">
                            {/*row 1*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', justifyContent: 'flex-start', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Length of Password
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>

                                    </Grid>

                                    <Grid item xs={12} s={12} md={12} lg={5} justifyContent="space-between" alignItems="right">
                                        <TextField
                                            fullWidth
                                            error={!!errors.passwordLength}
                                            helperText={errors.passwordLength}
                                            {...register("passwordLength",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_LENGTH).value,
                                                })}
                                            id='passwordLength'
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 2*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', justifyContent: 'flex-start', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                        Change Password (days)
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>

                                    </Grid>

                                    <Grid item xs={12} s={12} md={12} lg={5}justifyContent="space-between" alignItems="right">
                                        <TextField
                                            fullWidth
                                            error={!!errors.passwordDuration}
                                            helperText={errors.passwordDuration}
                                            {...register("passwordDuration",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_DURATION).value,
                                                })}
                                            id="passwordDuration"
                                            InputProps={{
                                                endAdornment: <InputAdornment position="end">days</InputAdornment>,
                                            }}
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 3*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', justifyContent: 'flex-start', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Password History
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>

                                    </Grid>

                                    <Grid item xs={12} s={12} md={12} lg={5}justifyContent="space-between" alignItems="right">
                                        <TextField
                                            fullWidth
                                            error={!!errors.passwordHistory}
                                            helperText={errors.passwordHistory}
                                            {...register("passwordHistory",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.PASSWORD_HISTORY).value,
                                                })}
                                            id="passwordHistory"
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 4*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', justifyContent: 'flex-start', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Maximum number of login failure
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>

                                    </Grid>

                                    <Grid item xs={12} s={12} md={12} lg={5}justifyContent="space-between" alignItems="right">
                                        <TextField
                                            fullWidth
                                            error={!!errors.maxLoginFailure}
                                            helperText={errors.maxLoginFailure}
                                            {...register("maxLoginFailure",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.LOGIN_ATTEMPT_LIMIT).value,
                                                })}
                                            id="maxLoginFailure"
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 5*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3}}>

                                    <Grid item xs={12} s={12} md={12} lg={5} sx={{ml:3, mr:3, display: 'flex', justifyContent: 'flex-start', alignItems: 'center'}}>
                                        <Typography variant="lionerSize" component="span">
                                            Penalty time of login failure (minutes)
                                        </Typography>
                                        <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>

                                    </Grid>

                                    <Grid item xs={12} s={12} md={12} lg={5}justifyContent="space-between" alignItems="right">
                                        <TextField
                                            fullWidth
                                            error={!!errors.loginFailPenaltyTime}
                                            helperText={errors.loginFailPenaltyTime}
                                            {...register("loginFailPenaltyTime",
                                                {
                                                    value: refRecord === null ? null : getObjectByName(refRecord,SETTING_STRING_DICT.LOGIN_ATTEMPT_PENALTY).value,
                                                })}
                                            id="loginFailPenaltyTime"
                                            InputProps={{
                                                endAdornment: <InputAdornment position="end">minutes</InputAdornment>,
                                            }}
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            <Grid item xs={12} s={12} md={12} lg={12} />

                            {/*row 7*/}
                            <Grid item xs={9}s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3, justifyContent: 'center', alignItems: 'center'}}>
                                    <Grid item xs={1} s={1} md={3} lg={3} />
                                    <Grid item xs={12} s={12} md={12} lg={11.8} justifyContent="flex-start" alignItems="center">
                                        <FormControlLabel sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}} control={
                                            <Switch
                                                onChange={(event, newValue) => {
                                                    setANonA(newValue);
                                                }}
                                                checked={aNonA}
                                            />
                                        }
                                         labelPlacement="start"
                                         label={
                                             <Typography variant="lionerSize" component="span">
                                                 Contain at least one alphabetic and non-alphabetic character
                                             </Typography>
                                         }/>
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 8*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3, justifyContent: 'center', alignItems: 'center'}}>
                                    <Grid item xs={1} s={1} md={3} lg={3} />
                                    <Grid item xs={12} s={12} md={12} lg={11.8} justifyContent="flex-start" alignItems="center">
                                        <FormControlLabel sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}} control={
                                            <Switch
                                                onChange={(event, newValue) => {
                                                    setNeedSpecialCharacter(newValue);
                                                }}
                                                checked={needSpecialCharacter}
                                            />
                                        }
                                        labelPlacement="start"
                                        label={
                                            <Typography variant="lionerSize" component="span">
                                                Contain at least one special character (eg. #,$,@ etc)</Typography>
                                        }
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 9*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3, justifyContent: 'center', alignItems: 'center'}}>
                                    <Grid item xs={1} s={1} md={3} lg={3} />
                                    <Grid item xs={12} s={12} md={12} lg={11.8} justifyContent="flex-start" alignItems="center">
                                        <FormControlLabel sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}} control={
                                            <Switch
                                                onChange={(event, newValue) => {
                                                    setNoUsernameAsPart(newValue);
                                                }}
                                                checked={noUsernameAsPart}
                                            />
                                        }
                                        labelPlacement="start"
                                        label={
                                            <Typography variant="lionerSize" component="span">
                                                Not contain the username as part of password
                                            </Typography>
                                        }
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*row 10*/}
                            <Grid item xs={9} s={12} md={9} lg={8} sx={{ml:3, mr:3, mb:3}}>
                                <Grid container sx={{mb:3, justifyContent: 'center', alignItems: 'center'}}>
                                    <Grid item xs={1} s={1} md={3} lg={3} />
                                    <Grid item xs={12} s={12} md={12} lg={11.8} justifyContent="flex-start" alignItems="center">
                                        <FormControlLabel sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}} control={
                                            <Switch
                                                onChange={(event, newValue) => {
                                                    setNoConsecutiveChar(newValue);
                                                }}
                                                checked={noConsecutiveChar}
                                            />
                                        }
                                        labelPlacement="start"
                                        label={
                                            <Typography variant="lionerSize" component="span">
                                                Contain no more than three identical consecutive characters
                                            </Typography>
                                        }
                                        />
                                    </Grid>
                                </Grid>
                                <Divider variant="middle" />
                            </Grid>

                            {/*last row*/}
                            <Grid item s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}} alignItems={"center"} justifyContent="center">
                                <ThemeProvider theme={LIONER_BUTTON_THEME}>
                                    <Grid container maxWidth justifyContent="flex-start">
                                        <Grid item sx={{ml:3, mr:3}}>
                                            <Button
                                                variant="contained"
                                                type="submit"
                                                color="save">
                                                Save
                                            </Button>
                                        </Grid>

                                        <Grid item sx={{ml:3, mr:3}}>
                                            <Button
                                                variant="contained"
                                                onClick={resetForm}
                                                color="cancel">
                                                Cancel
                                            </Button>
                                        </Grid>
                                    </Grid>
                                </ThemeProvider>
                            </Grid>
                        </Grid>
                    </form>
                </MainCard>
            </Grid>
            </ThemeProvider>
        </Grid>

    );
};

export default PasswordPolicyPage;
