import {useState} from "react";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import {Button, FormControl, Grid, IconButton, InputAdornment, TextField, Typography, InputLabel} from "@mui/material";
import {GENERAL_RED_COLOR} from "../../../../../themes/colorConst";
import DialogActions from "@mui/material/DialogActions";
import * as React from "react";
import {useForm} from "react-hook-form";
import {isObjEmpty} from "../../../../../utils/Utils";
import {CHANGE_PASSWORD_PATH} from "../../../../../utils/ApiPathConst";
import axios from "axios";
import {apiPath} from "../../../../../auth/utils";
import {notifySaveSuccess} from "../../../../../utils/CommonFunction";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
import Visibility from "@mui/icons-material/Visibility";
import {LIONER_FORM_THEME} from "../../../../../themes/themeConst";
import {ThemeProvider} from "@emotion/react";

export function ChangePasswordWindow({
                                                isWindowOpen,
                                                title,
                                                onNormalClose,
                                                onConfirmClose,
                                                isForce
                                     }){

    const [errors, setErrors] = useState({});
    const {reset, register, getValues} = useForm();
    const [showPassword, setShowPassword] = React.useState(false);
    const [showPassword2, setShowPassword2] = React.useState(false);
    const [showPassword3, setShowPassword3] = React.useState(false);

    const handleClickShowPassword = () => setShowPassword((show) => !show);
    const handleMouseDownPassword = () => setShowPassword(!showPassword);

    const handleClickShowPassword2 = () => setShowPassword2((show) => !show);
    const handleMouseDownPassword2 = () => setShowPassword2(!showPassword2);

    const handleClickShowPassword3 = () => setShowPassword3((show) => !show);
    const handleMouseDownPassword3 = () => setShowPassword3(!showPassword3);

    function updatePassword(){
        const values = getValues();
        axios.patch(`${apiPath}${CHANGE_PASSWORD_PATH}`,
            {
                "password": values.oldPassword,
                "newPassword": values.newPassword,
            })
            .then((response) => {
                if(response.status === 204){
                    notifySaveSuccess();
                    if(isForce){
                        localStorage.setItem('checkPasswordExpired', true);
                    }
                    reset();
                    onConfirmClose();
                }
            })
            .catch(error => {
                if (error.response.status === 422) {
                    const formErrors = {};
                    if(error.response.data.error === "Incorrect existing password"){
                        formErrors.oldPassword = error.response.data.error;
                    }
                    else{
                        formErrors.confirmPassword = error.response.data.error;
                    }
                    setErrors(formErrors);
                }
                //console.log(error);
                return true;
            });
    }

    function validate(){
        const values = getValues();
        const formErrors = {};
        console.log(values);
        if (isObjEmpty(values.oldPassword)) {
            formErrors.oldPassword = 'Existing password must not be null';
        }

        if (isObjEmpty(values.newPassword)) {
            formErrors.newPassword = 'New password must not be null';
        }

        if (isObjEmpty(values.confirmPassword)) {
            formErrors.confirmPassword = 'Confirm password must not be null';
        }

        if(values.newPassword !== values.confirmPassword){
            formErrors.confirmPassword = 'Password not match';
        }

        setErrors(formErrors);
        if (Object.keys(formErrors).length === 0) {
            updatePassword();
        }
    }

    return (
        <ThemeProvider theme={LIONER_FORM_THEME}>
        <Dialog
            PaperProps={{
                sx: {
                    minWidth:"40vw",
                    maxWidth: "70vw",
                    maxHeight: '70vh'
                }
            }}
            open={isWindowOpen}
            onClose={onNormalClose}
            disableEscapeKeyDown={isForce}
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
        >
            <DialogTitle id="alert-dialog-title">
                <InputLabel>
                    {title}
                </InputLabel>
            </DialogTitle>
            <DialogContent>
                <form>
                    <Grid container>
                        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml: 3, mr: 3, mb: 1}}>
                            <Grid container alignItems={"flex-start"}>
                                {
                                    isForce ?
                                        <Grid item xs={12} s={12} md={12} lg={12} sx={{mb:1}}>
                                            <div>
                                                <Typography variant="lionerSize" sx={{ color: GENERAL_RED_COLOR, ml:1 }} component="span">
                                                    The password has expired. Please update your password before using the system.
                                                </Typography>
                                            </div>
                                        </Grid>
                                        :
                                        undefined
                                }
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 1, mr: 3, mt:1.5, display: 'flex', alignItems: 'flex-start'}}>
                                    <InputLabel>
                                        Existing Password
                                    </InputLabel>
                                    <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={7}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            fullWidth
                                            type={showPassword ? 'text' : 'password'}
                                            {...register("oldPassword")}
                                            inputProps={{maxLength: 60}}
                                            id='oldPassword'
                                            size="small"
                                            error={!!errors.oldPassword}
                                            helperText={
                                                errors.oldPassword ? (
                                                    <Typography component="div" color="error">
                                                        {errors.oldPassword.split("\n").map((line, index) => {
                                                            return (
                                                                <Typography variant="lionerSize" key={index} >
                                                                    {line}
                                                                </Typography>
                                                            )
                                                        })}
                                                    </Typography>
                                                ) : null
                                            }
                                            InputProps={{
                                                endAdornment: (
                                                    <InputAdornment position="end">
                                                        <IconButton
                                                            aria-label="toggle password visibility"
                                                            onClick={handleClickShowPassword}
                                                            onMouseDown={handleMouseDownPassword}
                                                            edge="end"
                                                        >
                                                            {showPassword ? <Visibility />: <VisibilityOff />}
                                                        </IconButton>
                                                    </InputAdornment>
                                                )
                                            }}
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>

                            <Grid container alignItems={"flex-start"} sx={{mt:3}}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 1, mr: 3, mt:1.5, display: 'flex', alignItems: 'flex-start'}}>
                                    <InputLabel>
                                        New Password
                                    </InputLabel>
                                    <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={7}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            fullWidth
                                            type={showPassword2 ? 'text' : 'password'}
                                            {...register("newPassword")}
                                            inputProps={{maxLength: 60}}
                                            id='newPassword'
                                            size="small"
                                            error={!!errors.newPassword}
                                            helperText={
                                                errors.newPassword ? (
                                                    <Typography component="div" color="error">
                                                        {errors.newPassword.split("\n").map((line, index) => {
                                                            return (
                                                                <Typography variant="lionerSize" key={index} >
                                                                    {line}
                                                                </Typography>
                                                            )
                                                        })}
                                                    </Typography>
                                                ) : null
                                            }
                                            InputProps={{
                                                endAdornment: (
                                                    <InputAdornment position="end">
                                                        <IconButton
                                                            aria-label="toggle password visibility"
                                                            onClick={handleClickShowPassword2}
                                                            onMouseDown={handleMouseDownPassword2}
                                                            edge="end"
                                                        >
                                                            {showPassword2 ?<Visibility />: <VisibilityOff />}
                                                        </IconButton>
                                                    </InputAdornment>
                                                )
                                            }}
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>

                            <Grid container alignItems={"flex-start"} sx={{mt:3}}>
                                <Grid item xs={4} s={4} md={4} lg={4}
                                      sx={{ml: 1, mr: 3, mt:1.5, display: 'flex', alignItems: 'flex-start'}}>
                                    <InputLabel>
                                        Confirm Password
                                    </InputLabel>
                                    <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                                </Grid>

                                <Grid item xs={7} s={7} md={7} lg={7}>
                                    <FormControl  fullWidth required>
                                        <TextField
                                            fullWidth
                                            type={showPassword3 ? 'text' : 'password'}
                                            {...register("confirmPassword")}
                                            inputProps={{maxLength: 60}}
                                            id='confirmPassword'
                                            size="small"
                                            error={!!errors.confirmPassword}
                                            helperText={
                                                errors.confirmPassword ? (
                                                    <Typography component="div" color="error" variant="lionerSize">
                                                        {errors.confirmPassword.split("\n").map((line, index) => {
                                                            return (
                                                                <div  key={index} >
                                                                    {line}
                                                                </div>
                                                            )
                                                        })}
                                                    </Typography>
                                                ) : null
                                            }
                                            InputProps={{
                                                endAdornment: (
                                                    <InputAdornment position="end">
                                                        <IconButton
                                                            aria-label="toggle password visibility"
                                                            onClick={handleClickShowPassword3}
                                                            onMouseDown={handleMouseDownPassword3}
                                                            edge="end"
                                                        >
                                                            {showPassword3 ? <Visibility /> : <VisibilityOff />}
                                                        </IconButton>
                                                    </InputAdornment>
                                                )
                                            }}
                                        />
                                    </FormControl>
                                </Grid>
                            </Grid>
                        </Grid>
                    </Grid>
                </form>
            </DialogContent>
            <DialogActions>
                <Button onClick={onNormalClose} disabled={isForce}>Cancel</Button>
                <Button onClick={validate} autoFocus>
                    Confirm
                </Button>
            </DialogActions>
        </Dialog>
        </ThemeProvider>
    )
}