import React, { Component, Fragment } from 'react';
import { connect } from "react-redux";
import Validator from "validator";
import { subscribeToNewsletterRequest } from "../../actions/user";
import { Typography, Button } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';
import _ from "lodash";
import SendIcon from '@material-ui/icons/Send';
import TextField from '@material-ui/core/TextField';
import Snack from '../atoms/snack'

const styles = theme => ({
    root: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            flexDirection: 'row',
        },
    },
    text: {
        fontSize: '1.2em',
        fontWeight: '600',
        paddingRight: theme.spacing(2),
        paddingBottom: theme.spacing(3),
        '& span': {
            color: theme.palette.primary.main
        },
        [theme.breakpoints.up('sm')]: {
            width: '25%',
            paddingBottom: 0,
        },
    },
textField: {
    textAlign: 'center',
        justifyContent: 'center',
            margin: 0,
                '& input': {
        backgroundColor: theme.palette.background.grey,
            minWidth: '65vw',
                [theme.breakpoints.up('sm')]: {
            minWidth: 'inherit',
              },
    }
},
button: {
    padding: theme.spacing(2, 0),
    borderBottomLeftRadius: 0,
    borderTopLeftRadius: 0,
        boxShadown: '0px',
            backgroundColor: theme.palette.primary.dark,
},
sendIcon: {
    fill: theme.palette.background.grey,
},
newsletterForm: {
    display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: theme.palette.background.grey,
        margin: theme.spacing(0, 4),
        [theme.breakpoints.up('sm')]: {
            width: 'max-content',
        },
},
})

class NewsLetterRegistration extends Component {
    state = {
        data: {
            email: "",
        },
        success: false,
        errors: { message: "" },
        loading: false,
        tabIndex: 0,
        openSnack: false
    };

    UNSAFE_componentWillReceiveProps(nextProps) {

        this.setState({
            errors: !!!nextProps.errors ? { errors: { message: "" } } : nextProps.errors,
            loading: nextProps.loading,
            success: nextProps.success,
            openSnack: !_.isEmpty(nextProps.errors) || nextProps.success
        })
    }

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

    onSubmit = e => {
        e.preventDefault();
        const errors = this.validate(this.state.data);
        this.setState({ errors });
        if (Object.keys(errors).length === 0) {
            this.props.subscribeToNewsletterRequest(this.state.data)
        }
    };

    submit = data => { this.props.login(data) }

    validate = data => {
        const errors = {};
        if (!Validator.isEmail(data.email)) errors.email = "Invalid email";
        return errors;
    };

    handleClose = e =>
        this.setState({
            openSnack: false
        });

    render() {
        const { classes } = this.props;
        const { data, success, errors, loading, openSnack } = this.state;

        return (
            <section className={classes.root}>
                <Typography
                    gutterBottom
                    component="h3"
                    className={classes.text}
                >
                    Recevez les dernières nouvelles de <span>Talents Tube</span> par e-mail
                </Typography>
                <form className={classes.newsletterForm} onSubmit={this.onSubmit}>
                    <TextField
                        id="outlined-with-placeholder"
                        disabled={loading}
                        label="Newsletter"
                        name="email"
                        value={data.email}
                        onChange={this.onChange}
                        type="email"
                        placeholder="exemple@gmail.com"
                        className={classes.textField}
                        InputLabelProps={{
                            shrink: true,
                        }}
                        margin="dense"
                        variant="filled"
                    />
                    <Button type="submit"
                        name="registerToNewsletter"
                        disabled={loading}
                        variant="contained"
                        className={classes.button}
                    >
                        <SendIcon className={classes.sendIcon}/>
                    </Button >
                </form>
                <Snack name={success ? 'snackSuccess' : 'snackWarning'}
                    variant={success ? 'success' : 'warning'}
                    message={success ? 'Inscription validée.' : errors.message}
                    openSnack={openSnack}
                    onClose={this.handleClose} />
            </section>
        )
    }
}

function mapStateToProps(state, ownProps) {
    return {
        openSnack: !_.isEmpty(ownProps.errors),
        loading: !!state.user.loading,
        success: state.user.NewsLetterRegistrationSuccess,
        errors: state.user.errors || ownProps.errors
    };
}



export default (connect(mapStateToProps, { subscribeToNewsletterRequest })(withStyles(styles)(NewsLetterRegistration)));
