import React, { Component } from 'react'
import { withStyles } from '@material-ui/core/styles';
import Layout from '../components/templates/Layout';
import Loader from './../components/templates/loader'

import { connect } from "react-redux";
import Validator from "validator";
import { resetPasswordRequest } from "../actions/user";
import { TextField, Button, Typography } from '@material-ui/core';
import Snack from '../components/atoms/snack'
import _ from "lodash"
import Head from 'next/head'

const styles = theme => ({
    container: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        padding: theme.spacing(2),
        [theme.breakpoints.up('sm')]: {
            margin: 'auto',
            padding: '0 calc(25vw + 24px)',
            paddingBottom: theme.spacing(5),
        },
    },
    title: {
        fontFamily: 'Dosis',
        fontSize: '1.5em',
        fontWeight: '600',
        padding: theme.spacing(3, 0),
        [theme.breakpoints.up('sm')]: {
            paddingTop: theme.spacing(6),
        },
    },
    form: {
        display: 'flex',
        flexDirection: 'column',
        width: '100%',
    },
    input: {
        marginBottom: theme.spacing(4),
    },
    button: {
        textTransform: 'inherit',
        marginLeft: theme.spacing(8),
        marginRight: theme.spacing(8),
        padding: theme.spacing(1.2, 2),
        borderRadius: '3px',
        color: theme.palette.secondary.main,
        backgroundColor: theme.palette.primary.important,
        [theme.breakpoints.up('sm')]: {
            margin: 'auto',
        },
    },
})

class ResetPassword extends Component {

    state = {
        email: "",
        errors: {},
        loading: false,
        openErrorSnack: false,
        openSuccesSnack: false
    }

    onChange = e =>
        this.setState({ [e.target.name]: e.target.value });

    onSubmit = e => {
        e.preventDefault();
        const errors = this.validate(this.state.email);
        this.setState({ errors });
        if (Object.keys(errors).length === 0) {
            this.setState({ loading: true });

            this.props.resetPasswordRequest({ "username": this.state.email })
        }
    };

    validate = data => {
        const errors = {};
        if (!Validator.isEmail(data)) errors.email = "L'email ne convient pas.";

        return errors;
    };

    UNSAFE_componentWillReceiveProps(nextProps) {
        this.setState({
            errors: nextProps.errors,
            loading: nextProps.loading,
            openErrorSnack: !!!_.isEmpty(nextProps.errors),
            openSuccessSnack: nextProps.passwordReset,
        })
    }

    handleClose = (event, reason) => {
        this.setState({ openErrorSnack: false, openSuccessSnack: false });
    }

    render() {
        const { classes } = this.props;
        const { loading } = this.state;

        return (
            <Layout>
                <Head>
                    <title key="title">Reset password</title>
                    <meta key="robots" name="robots" content="noindex, nofollow"></meta>
                </Head>
                <div className={classes.container}>
                    <Typography
                        className={classes.title}
                        paragraph={true}
                        align="center"
                        variant="h5"
                    >
                        Réinitialisation du mot de passe
                    </Typography>

                    {loading && (
                        <Loader />
                    )}
                    {!loading && (
                        <form className={classes.form} onSubmit={this.onSubmit}>
                            <TextField
                                value={this.state.email}
                                id="email"
                                name="email"
                                label="Email"
                                margin="normal"
                                type="email"
                                value={this.state.email}
                                onChange={this.onChange}
                                autoComplete="username"
                                variant="outlined"
                                error={this.state.errors && !!this.state.errors.email}
                                className={classes.input}
                                required
                            />
                            <Button type="submit" variant="contained" className={classes.button}>
                                Réinitialiser le mot de passe
                    </Button>
                        </form>

                    )}
                </div>
                <Snack variant="error" message={!!!_.isEmpty(this.state.errors) && this.state.errors.message}
                    openSnack={this.state.openErrorSnack} onClose={this.handleClose} />
                <Snack variant="success" message={"Un email de réinitialisation vous a été envoyé."}
                    openSnack={this.state.openSuccessSnack} onClose={this.handleClose} />
            </Layout>
        )
    }
}

function mapStateToProps(state) {
    return {
        loading: !!state.user.loading,
        errors: state.user.errors,
        passwordReset: state.user.passwordReset
    };
}

export default withStyles(styles)(connect(mapStateToProps, { resetPasswordRequest })(ResetPassword));

