import { useFormik } from 'formik';
import * as yup from 'yup';
import * as React from "react";
import * as HttpUtils from "utils/HttpUtils";
import * as UrlUtils from "utils/ApiPathConst";
import { useNavigate } from "react-router-dom";

import {
    Grid,
    Typography,
    Button,
    // RadioGroup,
    Dialog, DialogTitle, DialogContent, DialogActions,
    Stack, 
    // InputLabel,
    // OutlinedInput,
    FormHelperText,
    TextField,
    IconButton, InputAdornment,
    CircularProgress,
    // Box,
    // FormControl
} from '@mui/material';
import Loadable from 'components/Loadable';
const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
// import ForwardIcon from '@mui/icons-material/Forward';
import MainCard from 'components/MainCard';
import {PNSPS_LONG_BUTTON_THEME} from "themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import {FormattedMessage, useIntl} from "react-intl";
import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';

import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import { useDispatch } from "react-redux";
import { handleLogoutFunction} from 'auth/index';
import { isPasswordExpiry } from "utils/Utils";
import usePageTitle from "components/usePageTitle";
// ==============================|| DASHBOARD - DEFAULT ||============================== //

const Index = () => {
    usePageTitle("userChangePassword");
    
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const [showPassword, setShowPassword] = React.useState(false);
    const [showNewPassword, setShowNewPassword] = React.useState(false);
    const [showConfirmPassword, setshowConfirmPassword] = React.useState(false);
    const [isLoading, setLoding] = React.useState(true);
    const [isChanged, setIsChanged] = React.useState(false);
    const [comfirmChangeMessage, setComfirmChangeMessage] = React.useState(false);
    const [expiryErr, setExpiryErr] = React.useState(false);
    const [expiryErrText, setExpiryErrText] = React.useState("");
    const [changePasswordValues, setChangePasswordValues] = React.useState();
    const [isChangingPassword, setIsChangingPassword] = React.useState(false);
    const changePwdInFlightRef = React.useRef(false);

    const intl = useIntl();
    
    React.useEffect(() => {
        setLoding(false)
    }, []);

    const goLogin = (values) =>{
        if (changePwdInFlightRef.current) {
            return;
        }
        changePwdInFlightRef.current = true;
        setIsChangingPassword(true);
        setComfirmChangeMessage(false);
        HttpUtils.post({
            url: UrlUtils.PATCH_CHANGE_PASSWORD,
            params:{
                password: values.password,
                newPassword: values.newPassword
            },
            onSuccess: function (){
                setIsChanged(true);
                changePwdInFlightRef.current = false;
                setIsChangingPassword(false);
            },
            onFail: function () {
                changePwdInFlightRef.current = false;
                setIsChangingPassword(false);
            },
            onError:function (error) {
                // console.log(error.response.data);
                setExpiryErrText(intl.formatMessage({ id: error.response.data.error }))
                setExpiryErr(true)
                changePwdInFlightRef.current = false;
                setIsChangingPassword(false);
                // window.location.assign("/iamsmart/loginFail");
            }
        });
    }

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

    const handleClickShowPassword = () => {
        setShowPassword(!showPassword);
    };

    const handleClickShowNewPassword = () => {
        setShowNewPassword(!showNewPassword);
    };

    const handleClickShowConfirmPassword = () => {
        setshowConfirmPassword(!showConfirmPassword);
    };

    const handleMouseDownPassword = (event) => {
        event.preventDefault();
    };

    const handleMouseDownNewPassword = (event) => {
        event.preventDefault();
    };

    const changePassword = (
        // value
        ) => {
        // const temp = strengthIndicator(value);
        // setLevel(strengthColorChi(temp));
    };

    const logout = () => {
        dispatch(handleLogoutFunction());
        navigate('/login');
    };

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            // username: '',
            password: '',
            newPassword: '',
            confirmPassword: '',
            // emailVerifyHash: '',
        },
        validationSchema: yup.object().shape({
            // emailVerifyHash: yup.string().required(intl.formatMessage({id: 'requireSecurityCode'})),
            // username: yup.string().required(intl.formatMessage({id: 'requireUsername'})),
            password: yup.string().min(8, intl.formatMessage({id: 'atLeast8CharPassword'}))
            .required(intl.formatMessage({id: 'requirePassword'}))
            .matches(/^\S*$/, { message: (intl.formatMessage({id: 'noSpacePassword'}))})
            .matches(/^(?=.*[a-z])/, { message: intl.formatMessage({id: 'atLeastOneSmallLetter'})})
            .matches(/^(?=.*[A-Z])/, { message: intl.formatMessage({id: 'atLeastOneCapLetter'})})
            .matches(/^(?=.*[0-9])/, { message: intl.formatMessage({id: 'atLeast1Number'})})
            .matches(/^(?=.*\W)/, { message: intl.formatMessage({id: 'atLeast1SpecialChar'})}),
            newPassword: yup.string().min(8, intl.formatMessage({id: 'atLeast8CharPassword'}))
            .required(intl.formatMessage({id: 'requirePassword'}))
            .matches(/^\S*$/, { message: (intl.formatMessage({id: 'noSpacePassword'}))})
            .matches(/^(?=.*[a-z])/, { message: intl.formatMessage({id: 'atLeastOneSmallLetter'})})
            .matches(/^(?=.*[A-Z])/, { message: intl.formatMessage({id: 'atLeastOneCapLetter'})})
            .matches(/^(?=.*[0-9])/, { message: intl.formatMessage({id: 'atLeast1Number'})})
            .matches(/^(?=.*\W)/, { message: intl.formatMessage({id: 'atLeast1SpecialChar'})}),
            confirmPassword: yup.string().min(8, intl.formatMessage({id: 'atLeast8CharPassword'}))
            .required(intl.formatMessage({id: 'pleaseConfirmPassword'}))
            .oneOf([yup.ref('newPassword'), null], intl.formatMessage({id: 'samePassword'})),
        }),
        onSubmit: values => {
            // console.log(values)
            setChangePasswordValues(values)
            setComfirmChangeMessage(true)
        }
    });

    const handleCCPChange = (e) => {
        e.preventDefault();
    };

    return (
        isLoading ?
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" justifyContent="center" alignItems="center">
                <Grid item>
                    <LoadingComponent />
                </Grid>
            </Grid>
            :
            <Grid container sx={{ minHeight: '87vh', mb: 3 }} direction="column" alignItems="center">
                <Grid item xs={12} md={12} width="100%" >
                    <div style={BackgroundHead}>
                        <Stack direction="row" height='70px' justifyContent="flex-start" alignItems="center">
                            <Typography component="h1" ml={15} color='#FFF' variant="h4" sx={{display: { xs: 'none', sm: 'none', md: 'block' }}}>
                                <FormattedMessage id="userChangePassword"/>
                            </Typography>
                        </Stack>
                    </div>
                </Grid>
                <Grid item xs={12} md={12} width={{ sx:"90%", sm:"90%",md: "60%", xs: "90%" }}>
                    <MainCard
                        sx={{
                        maxWidth: { xs: 400, sm:730, md:800, lg: 1000 },
                        margin: { sm: 0, md: 3 },
                        '& > *': {
                            flexGrow: 1,
                            flexBasis: '50%'
                        }
                        }}
                        content={false}
                        border={false}
                        boxShadow
                    >
                    {
                        !isChanged ?
                            <form onSubmit={formik.handleSubmit}>
                                <Grid container spacing={4} sx={{ minHeight: {xs:"80vh", sm:"50vh", md: "50vh", lg:"70vh", xl:"50vh"} }} direction="column" justifyContent="flex-start" alignItems="center">
                                    {isPasswordExpiry()?    
                                        <Grid item width="70%" xs={12} md={12} lg={12} sx={{ mb: 1, mt:2 }}>
                                            <Typography variant="h5" component="span">
                                                <FormattedMessage id="passwordExpired"/>
                                            </Typography>
                                        </Grid>
                                        : 
                                        <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:2 }}>
                                            <Typography variant="h5" component="span">
                                                <FormattedMessage id="setNewPassword"/>
                                            </Typography>
                                        </Grid>
                                    }
                                    <Grid item xs={12} md={12} lg={12} width={{xs:"70%", sm:"60%",md:"50%", lg:"50%"}}>
                                        <Grid container direction="row" justifyContent="flex-start">
                                            <Grid item xs={12} md={12} lg={12}>
                                                <TextField
                                                    fullWidth
                                                    autoFocus
                                                    onChange={(e) => {
                                                        formik.handleChange(e);
                                                        changePassword(e.target.value);
                                                    }}
                                                    id="password"
                                                    type={showPassword ? 'text' : 'password'}
                                                    name="password"
                                                    label={intl.formatMessage({id: 'oldPassword'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'oldPassword'})}
                                                    // defaultValue={formik.values.password.trim()}
                                                    value={formik.values.password.trim()}
                                                    error={Boolean(formik.touched.password && formik.errors.password)}
                                                    onBlur={formik.handleBlur}
                                                    inputProps={{
                                                        onKeyDown: (e) => {
                                                            if (e.key === 'Enter') {
                                                                e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                    InputLabelProps={{
                                                        shrink: true
                                                    }}
                                                    InputProps={{
                                                        endAdornment:(
                                                            <InputAdornment position="end">
                                                                <IconButton
                                                                    aria-label={intl.formatMessage({
                                                                        id: showPassword ? "ariaHidePassword" : "ariaShowPassword"
                                                                    })}
                                                                    onClick={handleClickShowPassword}
                                                                    onMouseDown={handleMouseDownPassword}
                                                                    edge="end"
                                                                    size="large"
                                                                >
                                                                    {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                                                </IconButton>
                                                            </InputAdornment>
                                                        )
                                                    }}
                                                />
                                            </Grid>
                                            {formik.touched.password && formik.errors.password && (
                                                <FormHelperText error id="helper-text-password-signup">
                                                    {formik.errors.password}
                                                </FormHelperText>
                                            )}
                                        </Grid>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} width={{xs:"70%", sm:"60%",md:"50%", lg:"50%"}}>
                                        <Grid container direction="row" justifyContent="flex-start">
                                            <Grid item xs={12} md={12} lg={12}>
                                                <TextField
                                                    fullWidth
                                                    // autoFocus
                                                    onChange={(e) => {
                                                        formik.handleChange(e);
                                                        changePassword(e.target.value);
                                                    }}
                                                    id="newPassword"
                                                    type={showNewPassword ? 'text' : 'password'}
                                                    name="newPassword"
                                                    label={intl.formatMessage({id: 'newPassword'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'newPassword'})}
                                                    // defaultValue={formik.values.password.trim()}
                                                    value={formik.values.newPassword.trim()}
                                                    error={Boolean(formik.touched.newPassword && formik.errors.newPassword)}
                                                    onBlur={formik.handleBlur}
                                                    inputProps={{
                                                        onKeyDown: (e) => {
                                                            if (e.key === 'Enter') {
                                                                e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                    InputLabelProps={{
                                                        shrink: true
                                                    }}
                                                    InputProps={{
                                                        endAdornment:(
                                                            <InputAdornment position="end">
                                                                <IconButton
                                                                    aria-label={intl.formatMessage({ id: 'ariaToggleNewPasswordVisibility' })}
                                                                    onClick={handleClickShowNewPassword}
                                                                    onMouseDown={handleMouseDownNewPassword}
                                                                    edge="end"
                                                                    size="large"
                                                                >
                                                                    {showNewPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                                                </IconButton>
                                                            </InputAdornment>
                                                        )
                                                    }}
                                                />
                                            </Grid>
                                            {formik.touched.newPassword && formik.errors.newPassword && (
                                                <FormHelperText error id="helper-text-newPassword-signup">
                                                    {formik.errors.newPassword}
                                                </FormHelperText>
                                            )}
                                        </Grid>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} width={{xs:"70%", sm:"60%",md:"50%", lg:"50%"}}>
                                        <Grid container direction="row" justifyContent="flex-start">
                                            <Grid item xs={12} md={12} lg={12}>
                                                <TextField
                                                    fullWidth
                                                    onChange={(e) => {
                                                        formik.handleChange(e);
                                                        // changePassword(e.target.value);
                                                    }}
                                                    id="confirmPassword"
                                                    type={showConfirmPassword ? 'text' : 'password'}
                                                    name="confirmPassword"
                                                    label={intl.formatMessage({id: 'confirmNewPassword'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'confirmNewPassword'})}
                                                    // defaultValue={formik.values.confirmPassword.trim()}
                                                    value={formik.values.confirmPassword.trim()}
                                                    error={Boolean(formik.touched.confirmPassword && formik.errors.confirmPassword)}
                                                    onBlur={formik.handleBlur}
                                                    onCut={handleCCPChange}
                                                    onCopy={handleCCPChange}
                                                    onPaste={handleCCPChange}
                                                    inputProps={{
                                                        maxLength: 50,
                                                        onKeyDown: (e) => {
                                                            // console.log(e)
                                                            if (e.key === 'Enter') {
                                                                e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                    InputLabelProps={{
                                                        shrink: true
                                                    }}
                                                    InputProps={{
                                                        endAdornment:( 
                                                            <InputAdornment position="end">
                                                                <IconButton
                                                                    aria-label={intl.formatMessage({
                                                                        id: showConfirmPassword ? "ariaHidePassword" : "ariaShowPassword"
                                                                    })}
                                                                    onClick={handleClickShowConfirmPassword}
                                                                    onMouseDown={handleMouseDownPassword}
                                                                    edge="end"
                                                                    size="large"
                                                                >
                                                                    {showConfirmPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                                                </IconButton>
                                                            </InputAdornment>
                                                        )
                                                    }}
                                                />
                                            </Grid>
                                            {formik.touched.confirmPassword && formik.errors.confirmPassword && (
                                                <FormHelperText error id="helper-text-confirmPassword-signup">
                                                    {formik.errors.confirmPassword}
                                                </FormHelperText>
                                            )}
                                        </Grid>
                                        <Grid container spacing={2} alignItems="center">
                                            <Grid item sx={{ mt: 1 }}>
                                                <Typography variant="subtitle1" component="p">
                                                    •<FormattedMessage id="pwRemark1" /><br />
                                                    •<FormattedMessage id="pwRemark2" /><br />
                                                    •<FormattedMessage id="pwRemark3" /><br />
                                                    •<FormattedMessage id="pwRemark4" /><br />
                                                    •<FormattedMessage id="pwRemark5"/><br />
                                                </Typography>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} mt={1} sx={{mb:3}}>
                                        <ThemeProvider theme={PNSPS_LONG_BUTTON_THEME}>
                                            <Button
                                                aria-label={intl.formatMessage({id: 'confirm'})}
                                                variant="contained"
                                                type="submit"
                                                disabled={isChangingPassword}
                                                // onClick={()=>goLogin()}
                                            >
                                                <FormattedMessage id="confirm"/>
                                            </Button>
                                        </ThemeProvider>
                                    </Grid>
                                </Grid>
                                <div>
                                    <Dialog
                                        open={comfirmChangeMessage}
                                        onClose={() => setComfirmChangeMessage(false)}
                                        PaperProps={{
                                            sx: {
                                                minWidth: '40vw',
                                                maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                                                maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                                            }
                                        }}
                                    >
                                        <DialogTitle></DialogTitle>
                                        <DialogContent style={{ display: 'flex', }}>
                                            <Stack direction="column" justifyContent="space-between">
                                                <Typography variant="h5" component="span" style={{ padding: '10px' }}>
                                                    <FormattedMessage id ="changePasswordConfirm"/>
                                                </Typography>
                                            </Stack>
                                        </DialogContent>
                                        <DialogActions>
                                            <Button disabled={isChangingPassword} onClick={() => setComfirmChangeMessage(false)}>
                                                <Typography variant="h5" component="span">
                                                    <FormattedMessage id="close"/>
                                                </Typography>
                                            </Button>
                                            <Button
                                                disabled={isChangingPassword}
                                                onClick={() => goLogin(changePasswordValues)}
                                                startIcon={isChangingPassword ? <CircularProgress color="inherit" size={18} /> : null}
                                            >
                                                <Typography variant="h5" component="span">
                                                    <FormattedMessage id="confirm"/>
                                                </Typography>
                                            </Button>
                                        </DialogActions>
                                    </Dialog>

                                    <Dialog
                                        open={expiryErr}
                                        onClose={() => setExpiryErr(false)}
                                        PaperProps={{
                                            sx: {
                                                minWidth: '40vw',
                                                maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                                                maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                                            }
                                        }}
                                    >
                                        <DialogTitle>
                                            <Typography variant="h5" component="span" style={{ padding: '10px' }}>
                                                <FormattedMessage id ="MSG.actionFail"/>
                                            </Typography>
                                        </DialogTitle>
                                        <DialogContent style={{ display: 'flex', }}>
                                            <Stack direction="column" justifyContent="space-between">
                                                <Typography variant="h5" component="span">
                                                    {
                                                        expiryErrText
                                                    }
                                                </Typography>
                                            </Stack>
                                        </DialogContent>
                                        <DialogActions>
                                            <Button onClick={() => setExpiryErr(false)}>
                                                <Typography variant="h5" component="span">
                                                    <FormattedMessage id="close"/>
                                                </Typography>
                                            </Button>
                                        </DialogActions>
                                    </Dialog>
                                </div>
                            </form>
                        :
                            <Grid container spacing={4} sx={{ minHeight: {xs:"80vh", sm:"70vh", md: "70vh", lg:"70vh", xl:"50vh"} }} direction="column" justifyContent="flex-start" alignItems="center">
                                <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5, }}>
                                        {/* <Button disabled={true} hidden={true} variant="contained" type="submit" sx={{ fontSize: 12,height:'25px'}}>Submit</Button> */}
                                    <CheckCircleOutlineIcon color="success" sx={{ width: "200px", height: "200px" }} />
                                </Grid>
                                <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5,}}>
                                    <Typography display="inline" variant="h4" component="span">
                                        <FormattedMessage id="resetPasswordSuccess"/>
                                    </Typography>
                                </Grid>
                                <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5,}}>
                                    <Button color="success" variant="outlined" onClick={()=>logout()}>
                                        <Typography variant="h5" component="span">
                                            <FormattedMessage id="backToLogin"/>
                                        </Typography>
                                    </Button>
                                </Grid>
                            </Grid>
                    }
                        
                    </MainCard>
                </Grid>
            </Grid>
    );
};

export default Index;