// material-ui
import {
    Grid,
    Typography,
    Button,
    // RadioGroup,
    Dialog, DialogTitle, DialogContent, DialogActions,
    Stack, 
    InputLabel,
    // OutlinedInput,
    FormHelperText,
    TextField,
    // Box
} from '@mui/material';
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 * as FieldUtils from "utils/FieldUtils";
import titleBackgroundImg from 'assets/images/dashboard/gazette-bar.png'
import ForwardIcon from '@mui/icons-material/Forward';
import MainCard from 'components/MainCard';


import { useNavigate } from "react-router-dom";
// import { notifyActionSuccess } from 'utils/CommonFunction';
import {PNSPS_LONG_BUTTON_THEME} from "themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import {FormattedMessage, useIntl} from "react-intl";

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

const ForgotUsernameApplyForm = () => {
    const [isWarningPopUp, setIsWarningPopUp] = React.useState(false);
    const [isSubmitting, setIsSubmitting] = React.useState(false);
    const submittingRef = React.useRef(false);
    // const [warningText, setWarningText] = React.useState("");s
    // const [attachment, setAttachment] = React.useState({});
    const intl = useIntl();

    // const [issueId, setIssueId] = React.useState(loadedData.issueId);
    const navigate = useNavigate();

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

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            // username: '',
            emailAddress: '',
        },
        validationSchema: yup.object().shape({
            // username: yup.string().required(intl.formatMessage({id: 'requireUsername'})),
            emailAddress: yup.string().email(intl.formatMessage({id: 'validEmailFormat'})).max(255).required(intl.formatMessage({id: 'requireEmail'})),
        }),
        onSubmit: values => {
            if (submittingRef.current) return;
            submittingRef.current = true;
            // console.log(values)
            setIsSubmitting(true);
            HttpUtils.post({
                url: UrlUtils.POST_FORGOT_USERNAME_EMAIL,
                params: {
                    emailAddress: values.emailAddress,
                },
                // files: [attachment],
                onSuccess: function () {
                    submittingRef.current = false;
                    setIsSubmitting(false);
                    // notifyActionSuccess(intl.formatMessage({id: 'submissionSuccess'}) + '!')
                    navigate('/forgot/username/sent');
                    // location.reload(); 
                },
                onError: function () {
                    submittingRef.current = false;
                    setIsSubmitting(false);
                    navigate('/forgot/username/sent');
                }
            });
        }
    });

    return (
        <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="forgotUsername"/>
                        </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} md={12} width={{ md: "60%", xs: "90%" }}>
                <MainCard
                    sx={{
                    maxWidth: { xs: 400, sm:600, md:800, lg: 1000 },
                    margin: { sm: 2.5, md: 3 },
                    '& > *': {
                        flexGrow: 1,
                        flexBasis: '50%'
                    }
                    }}
                    content={false}
                    border={false}
                    boxShadow
                >
                    <form onSubmit={formik.handleSubmit}>
                        <Grid container spacing={2} sx={{ minHeight: '40vh' }} 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' } }}>
                                <InputLabel htmlFor="email-login-title">
                                    <Typography variant="h5" >
                                        <FormattedMessage id="forgotUsernameSubTitle"/>
                                    </Typography>
                                </InputLabel>
                            </Grid>
                            <Grid item xs={12} md={12} lg={12} sx={{ mb: 1, mt:5, display: { md: 'none', xl: 'none', lg: 'none' } }}>
                                <InputLabel htmlFor="email-login-subtitle">
                                    <Typography variant="h6" >
                                        <FormattedMessage id="forgotUsernameSubTitle1"/>
                                    </Typography>
                                    <Typography variant="h6" >
                                        <FormattedMessage id="forgotPasswordSubTitle2"/>
                                    </Typography>
                                </InputLabel>
                            </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} sx={{ mb: 3}} >
                                        <TextField
                                            fullWidth
                                            autoFocus
                                            onChange={formik.handleChange}
                                            id="emailAddress"
                                            name="emailAddress"
                                            placeholder={intl.formatMessage({id: 'userContactEmail'})}
                                            label={intl.formatMessage({id: 'userContactEmail'}) + ":"}
                                            defaultValue={formik.values.emailAddress}
                                            value={formik.values.emailAddress}
                                            error={Boolean(formik.touched.emailAddress && formik.errors.emailAddress)}
                                            onBlur={formik.handleBlur}
                                            inputProps={{
                                                "aria-describedby" : 'standard-weight-helper-text-emailAddress-login',
                                                "aria-label": intl.formatMessage({id: 'userContactEmail'}),
                                                maxLength: 50,
                                                onKeyDown: (e) => {
                                                    if (e.key === 'Enter') {
                                                    e.preventDefault();
                                                    }
                                                },
                                            }}
                                            InputLabelProps={{
                                                shrink: true
                                            }}
                                        />
                                    </Grid>
                                    {formik.touched.emailAddress && formik.errors.emailAddress && (
                                        <FormHelperText error id="standard-weight-helper-text-emailAddress-login">
                                        {formik.errors.emailAddress}
                                        </FormHelperText>
                                    )}
                                </Grid>
                            </Grid>
                            <Grid item xs={12} md={12} lg={12} mt={1}>
                                <ThemeProvider theme={PNSPS_LONG_BUTTON_THEME}>
                                    <Button
                                        aria-label={intl.formatMessage({id: 'continue'})}
                                        variant="contained"
                                        type="submit"
                                        disabled={isSubmitting}
                                    >
                                        {isSubmitting ? <FormattedMessage id="loading"/> : <FormattedMessage id="continue"/>}
                                    </Button>
                                </ThemeProvider>
                            </Grid>
                        </Grid>
                    </form>
                </MainCard>
            </Grid>
            <div>
                <Dialog
                    open={isWarningPopUp}
                    onClose={() => setIsWarningPopUp(false)}
                    PaperProps={{
                        sx: {
                            minWidth: '40vw',
                            maxWidth: { xs: '90vw', s: '90vw', m: '70vw', lg: '70vw' },
                            maxHeight: { xs: '90vh', s: '70vh', m: '70vh', lg: '60vh' }
                        }
                    }}
                >
                    <DialogTitle>
                        <FormattedMessage id="attention"/>
                    </DialogTitle>
                    <DialogContent style={{ display: 'flex', }}>
                        {/* <Typography variant="h5" style={{ padding: '16px' }}>{warningText}</Typography> */}
                    </DialogContent>
                    <DialogActions>
                        <Button
                            aria-label={intl.formatMessage({id: 'close'})}
                            onClick={() => setIsWarningPopUp(false)}
                        >
                            <FormattedMessage id="close" />
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        </Grid>
    );
};


export default ForgotUsernameApplyForm;
