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,
    //  handleLogin
     } from 'auth/index';
import useJwt from "auth/jwt/useJwt";

import {
    Grid,
    Typography,
    Button,
    // RadioGroup,
    // Dialog, DialogTitle, DialogContent, DialogActions,
    Stack, 
    InputLabel,
    // OutlinedInput,
    FormHelperText,
    TextField,
    IconButton, InputAdornment,
    // 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 axios from 'axios';
import { useParams,Link } from 'react-router-dom';
import CancelOutlinedIcon from '@mui/icons-material/CancelOutlined';

// ==============================|| 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);
    const [verifyState, setVerifyState] = React.useState(null)
    const [enterUseEffect, setEnterUseEffect] = React.useState(false)
    const [username, setUsername] = React.useState("")
    // const { setLocale } = React.useContext(LocaleContext);
    
    const params = useParams()
    const intl = useIntl();
    
    React.useEffect(() => {
        // console.log(params);
        setEnterUseEffect(true)
    }, []);

    React.useEffect(() => {
        // console.log("if (enterUseEffect) handleVerify()");
        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) {
                    // console.log(response)
                    setUsername(response.data.username)
                    setVerifyState(true)
                } else {
                    setVerifyState(false)
                }
                setLoding(false)
            }
        ).catch(error => {
            console.log(error)
            setVerifyState(false)
            setLoding(false)
        });

        
    }

    const goLogin = async (values) =>{
        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()
                    // setSumitting(false)
                    })
                    .catch((error) => {
                    console.error(error)
                    });
            },
            onFail: (response)=>{
                console.log("Fail");
                console.log(response);
                window.location.assign("/iamsmart/loginFail");
            },
            onError:(error)=>{
                console.log(error);
                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));
    };

    function getMaxErrStr(num, fieldname){
        return intl.formatMessage({ id: 'noMoreThenNWords' },{num:num, fieldname:fieldname?intl.formatMessage({ id: fieldname})+": ":""});
    }
    

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            // username: '',
            password: '',
            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'}))
            .max(60, getMaxErrStr(60))
            .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'}))
            .max(60, getMaxErrStr(60))
            .required(intl.formatMessage({id: 'pleaseConfirmPassword'}))
            .oneOf([yup.ref('password'), null], intl.formatMessage({id: 'samePassword'})),
        }),
        onSubmit: values => {
            // console.log(values)
            goLogin(values)
        }
    });

    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} width={{xs:"90%", sm:"90%", md:"60%", lg:"60%"}}>
                    <Button
                        aria-label={intl.formatMessage({id: 'back'})}
                        title={intl.formatMessage({id: 'back'})}
                        sx={{ ml: 0, mt: 2.5 }} style={{ border: '2px solid' }} variant="outlined" onClick={() => { navigate(-1) }}
                    >
                        <ForwardIcon style={{ height: 30, width: 50, transform: "rotate(180deg)" }} />
                    </Button>
                </Grid> */}
                {/* <Grid item xs={12}>
                        <Typography variant="pnspsFormParagraphBold">申請公共啟事</Typography>
                    </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 ?
                                // 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
                                                    onChange={formik.handleChange}
                                                    id="emailVerifyHash"
                                                    name="emailVerifyHash"
                                                    label={intl.formatMessage({id: 'securityCode'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'securityCode'})}
                                                    defaultValue={formik.values.emailVerifyHash}
                                                    value={formik.values.emailVerifyHash}
                                                    error={Boolean(formik.touched.emailVerifyHash && formik.errors.emailVerifyHash)}
                                                    onBlur={formik.handleBlur}
                                                    inputProps={{
                                                        maxLength: 50,
                                                        onKeyDown: (e) => {
                                                            if (e.key === 'Enter') {
                                                            e.preventDefault();
                                                            }
                                                        },
                                                    }}
                                                    InputLabelProps={{
                                                        shrink: true
                                                    }}
                                                />
                                            </Grid>
                                            {formik.touched.emailVerifyHash && formik.errors.emailVerifyHash && (
                                                <FormHelperText error id="standard-weight-helper-text-username-login">
                                                {formik.errors.emailVerifyHash}
                                                </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
                                                    id="username"
                                                    name="username"
                                                    label={intl.formatMessage({id: 'userLoginName'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'userLoginName'})}
                                                    // defaultValue={username}
                                                    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'})}
                                                    // 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>
                                            {/* <FormControl fullWidth sx={{ mt: 2 }}>
                                                <Grid container spacing={2} alignItems="center">
                                                    <Grid item>
                                                        <Box sx={{ bgcolor: level?.color, width: 85, height: 8, borderRadius: '7px' }} />
                                                    </Grid>
                                                    <Grid item>
                                                        <Typography variant="subtitle1">
                                                            <FormattedMessage id={level ? level?.label : "pwWeak" }/>
                                                        </Typography>
                                                    </Grid>
                                                </Grid>
                                            </FormControl> */}
                                            {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);
                                                        // changePassword(e.target.value);
                                                    }}
                                                    id="confirmPassword"
                                                    type={showConfirmPassword ? 'text' : 'password'}
                                                    name="confirmPassword"
                                                    label={intl.formatMessage({id: 'confirmPassword'}) + ":"}
                                                    placeholder={intl.formatMessage({id: 'confirmPassword'})}
                                                    // defaultValue={formik.values.confirmPassword.trim()}
                                                    value={formik.values.confirmPassword.trim()}
                                                    error={Boolean(formik.touched.confirmPassword && formik.errors.confirmPassword)}
                                                    onBlur={formik.handleBlur}
                                                    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>
                                    <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"
                                                // onClick={()=>goLogin()}
                                            >
                                                <FormattedMessage id="confirm"/>
                                            </Button>
                                        </ThemeProvider>
                                    </Grid>
                                </Grid>
                                :
                                // ERROR page
                                <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, display: { xs: 'none', sm: 'none', md: 'block' } }}>
                                         {/* <Button disabled={true} hidden={true} variant="contained" type="submit" sx={{ fontSize: 12,height:'25px'}}>Submit</Button> */}
                                        <CancelOutlinedIcon color="error" sx={{ width: "200px", height: "200px" }} />
                                    </Grid>  
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5, ml:2, display: { xs: 'none', sm: 'none', md: 'block' } }}>
                                        <Typography display="inline" variant="h4">
                                            <FormattedMessage id="verifyFail"/>
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5, display: { xs: 'none', sm: 'none', md: 'block' } }}>
                                        <Button color="error" variant="outlined" component={Link} to="/login">
                                            <Typography variant="h5">
                                                <FormattedMessage id="backToLogin"/>
                                            </Typography>
                                        </Button>
                                    </Grid>
                                </Grid>
                            }
                            
                            <Grid container spacing={4} sx={{ minHeight: {xs:"80vh", sm:"70vh", md: "70vh", lg:"70vh", xl:"50vh"} }} direction="column" justifyContent="flex-start" alignItems="center">
                                
                            </Grid>
                        </form>
                    </MainCard>
                </Grid>
            </Grid>
    );
};

export default Index;