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 { useDispatch } from "react-redux";
import { handleLogoutFunction,

     } from 'auth/index';
import useJwt from "auth/jwt/useJwt";

import {
    Grid,
    Typography,
    Button,
    Stack, 
    InputLabel,

    FormHelperText,
    TextField,
    IconButton, InputAdornment,
    CircularProgress,

} 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 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 axios from 'axios';
import { useParams,Link } from 'react-router-dom';
import CancelOutlinedIcon from '@mui/icons-material/CancelOutlined';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';


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

const Index = () => {
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const [showPassword, setShowPassword] = React.useState(false);
    const [showConfirmPassword, setshowConfirmPassword] = React.useState(false);
    const [isLoading, setLoding] = React.useState(true);
    /** null: loading; true: verified (show password form); false: link invalid/already used (HTTP 200, no username); 'error': network / server error */
    const [verifyState, setVerifyState] = React.useState(null)
    const [enterUseEffect, setEnterUseEffect] = React.useState(false)
    const [username, setUsername] = React.useState("")
    const [isSubmitting, setIsSubmitting] = React.useState(false)
    const submittingRef = React.useRef(false)

    
    const params = useParams()
    const intl = useIntl();
    
    React.useEffect(() => {
        // console.log(params);
        setEnterUseEffect(true)
    }, []);

    React.useEffect(() => {
        if (enterUseEffect){
            handleVerify()
        } 
    }, [enterUseEffect])

    const handleVerify = async () => {
        // console.log(params);
        await axios.get(UrlUtils.GET_FORGOT_PASSWORD_VERIFY_USER_ACCOUNT, {
            params: {
                email: decodeURIComponent(params.email),
                emailVerifyHash: decodeURIComponent(params.verifyCode)
            }
        }        ).then(
            (response)=>{
                if (response.status === 200 && response.data && response.data.username) {
                    console.log(response)
                    setUsername(response.data.username)
                    setVerifyState(true)
                } else if (response.status === 200) {
                    setVerifyState(false)
                } else {
                    setVerifyState('error')
                }
                setLoding(false)
            }
        ).catch(error => {
            console.log(error)
            setVerifyState('error')
            setLoding(false)
        });

        
    }

    const goLogin = async (values) =>{
        if (submittingRef.current) return;
        submittingRef.current = true;
        setIsSubmitting(true);
        dispatch(handleLogoutFunction());
        HttpUtils.post({
            url: UrlUtils.POST_FORGOT_PASSWORD_NEW_PASSWORD,
            params:{
                username: username,
                newPassword: values.password
            },
            onSuccess: () => {
                useJwt
                .login({ username: username, password: values.password })
                .then((
                    // response
                    ) => {
                // console.log(response)
                    navigate('/forgot/password/success');
                    location.reload()
                    })
                    .catch((error) => {
                    console.error(error)
                    submittingRef.current = false;
                    setIsSubmitting(false);
                    });
            },
            onFail: (response)=>{
                console.log("Fail");
                console.log(response);
                submittingRef.current = false;
                setIsSubmitting(false);
                window.location.assign("/iamsmart/loginFail");
            },
            onError:(error)=>{
                console.log(error);
                submittingRef.current = false;
                setIsSubmitting(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 handleClickShowConfirmPassword = () => {
        setshowConfirmPassword(!showConfirmPassword);
    };

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

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

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            password: '',
            confirmPassword: '',
        },
        validationSchema: yup.object().shape({
            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'})}),
            confirmPassword: yup.string().min(8, intl.formatMessage({id: 'atLeast8CharPassword'}))
            .required(intl.formatMessage({id: 'pleaseConfirmPassword'}))
            .oneOf([yup.ref('password'), null], intl.formatMessage({id: 'samePassword'})),
        }),
        onSubmit: values => {
            // console.log(values)
            goLogin(values)
        }
    });

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

    return (
        isLoading || verifyState == null ?
            <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="forgotUserPassword"/>
                            </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
                    >
                        <form onSubmit={formik.handleSubmit}>
                            {verifyState === true ?
                                // SUCCESS page
                                <Grid container spacing={4} sx={{ minHeight: {xs:"80vh", sm:"50vh", md: "50vh", lg:"70vh", xl:"50vh"} }} direction="column" justifyContent="flex-start" alignItems="center">
                                    <Grid container direction="column" alignItems="center">
                                        <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5, }}>
                                            <Typography display="inline" variant="h4">
                                                <FormattedMessage id="verifySuccess"/>
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12} md={12} lg={12} sx={{ mb: 1,}}>
                                            <InputLabel htmlFor="email-login-title3">
                                                <Typography variant="h5" >
                                                    <FormattedMessage id="setNewPassword"/>
                                                </Typography>
                                            </InputLabel>
                                        </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
                                                    id="username"
                                                    name="username"
                                                    label={intl.formatMessage({id: 'userLoginName'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'userLoginName'})}
                                  
                                                    value={username}
                                                    disabled={true}                                                />
                                            </Grid>
                                        </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="password"
                                                    type={showPassword ? 'text' : 'password'}
                                                    name="password"
                                                    label={intl.formatMessage({id: 'newPassword'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'newPassword'})}
                                       
                                                    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
                                                    onChange={(e) => {
                                                        formik.handleChange(e);
                                                  
                                                    }}
                                                    id="confirmPassword"
                                                    type={showConfirmPassword ? 'text' : 'password'}
                                                    name="confirmPassword"
                                                    label={intl.formatMessage({id: 'confirmPassword'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'confirmPassword'})}
                                           
                                                    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) => {
                                                            if (e.key === 'Enter') {
                                                            e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                    InputLabelProps={{
                                                        shrink: true
                                                    }}
                                                    InputProps={{
                                                        endAdornment:( 
                                                            <InputAdornment position="end">
                                                                <IconButton
                                                                    aria-label={intl.formatMessage({
                                                                        id: showConfirmPassword ? "ariaHidePassword" : "ariaShowPassword"
                                                                    })}
                                                                    aria-describedby="helper-text-confirmPassword-signup"
                                                                    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">
                                                    •<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={isSubmitting}
                                                startIcon={isSubmitting ? <CircularProgress color="inherit" size={20} /> : null}
                                            >
                                                {isSubmitting ? <FormattedMessage id="loading"/> : <FormattedMessage id="confirm"/>}
                                            </Button>
                                        </ThemeProvider>
                                    </Grid>
                                </Grid>
                                : verifyState === false ?
                                // Link invalid or already used (same as Verify.js informational branch)
                                <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,}}>
                                        <InfoOutlinedIcon color="info" sx={{ width: "200px", height: "200px" }} />
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5, ml:2}}>
                                        <Typography display="inline" variant="h4" sx={{textAlign: 'justify'}}>
                                            <FormattedMessage id="verifyInfo"/>
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5,}}>
                                        <Button variant="outlined" component={Link} to="/login" color="primary">
                                            <Typography variant="h5">
                                                <FormattedMessage id="backToLogin"/>
                                            </Typography>
                                        </Button>
                                    </Grid>
                                </Grid>
                                :
                                // ERROR page (network / server error)
                                <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,}}>
                                        <CancelOutlinedIcon color="error" sx={{ width: "200px", height: "200px" }} />
                                    </Grid>  
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5, ml:2}}>
                                        <Typography display="inline" variant="h4" sx={{textAlign: 'justify'}}>
                                            <FormattedMessage id="verifyFail"/>
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5,}}>
                                        <Button color="error" variant="outlined" component={Link} to="/login">
                                            <Typography variant="h5">
                                                <FormattedMessage id="backToLogin"/>
                                            </Typography>
                                        </Button>
                                    </Grid>
                                </Grid>
                            }
                        </form>
                    </MainCard>
                </Grid>
            </Grid>
    );
};

export default Index;