import React, { Fragment } from 'react';
import clsx from 'clsx';
import { connect } from "react-redux";
import Validator from "validator";
import { TextField, FormControlLabel, Checkbox, Button, Typography, Link } from '@material-ui/core';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import IconButton from '@material-ui/core/IconButton';
import InputAdornment from '@material-ui/core/InputAdornment';
import { withStyles } from '@material-ui/core/styles';
import { registerUserRequest, subscribeToNewsletterRequest } from "../../actions/user"
import SocialButtonsAuth from '../atoms/SocialButtonsAuth';

const styles = theme => ({
    container: {
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
        paddingTop: theme.spacing(4),
        [theme.breakpoints.up('sm')]: {
            padding: '5vw 10vw',
        },
        [theme.breakpoints.up('md')]: {
            padding: '5vw 25vw',
        },
    },
    textField: {
        width: '100%'
    },
    form: {
        display: 'flex',
        flexDirection: 'column',
    },
    formText: {
        padding: theme.spacing(0, 2),
        paddingTop: theme.spacing(3),
        fontSize: '0.9em',
        fontWeight: '300',
    },
    formLink: {
        paddingLeft: theme.spacing(1),
        fontWeight: '500',
        color: theme.palette.primary.dark,
    },
    checkbox: {
        display: 'flex',
        alignItems: 'center',

        '& .MuiFormControlLabel-label': {
            fontSize: '0.9em',
            fontWeight: '500',
            color: theme.palette.primary.dark,
        }
    },
    checkboxError: {
        '& .MuiFormControlLabel-label': {
            color: 'red'
        }
    },
    conditionalText: {
        display: 'flex',
        flexDirection: 'row',
        color: theme.palette.primary.conditional,
        textTransform: 'uppercase',

        '&:before': {
            content: '""',
            flex: '1 1',
            borderBottom: '1px solid',
            borderColor: theme.palette.primary.conditional,
            marginRight: '10px',
            marginTop: 'auto',
            marginBottom: 'auto',
        },
        '&:after': {
            content: '""',
            flex: '1 1',
            borderBottom: '1px solid',
            borderColor: theme.palette.primary.conditional,
            marginLeft: '10px',
            marginTop: 'auto',
            marginBottom: 'auto',
        },
    },
    button: {
        textTransform: 'inherit',
        marginLeft: theme.spacing(10),
        marginRight: theme.spacing(10),
        marginTop: theme.spacing(4),
        marginBottom: theme.spacing(2),
        padding: theme.spacing(1.2, 1),
        borderRadius: '3px',
        color: theme.palette.secondary.main,
        backgroundColor: theme.palette.primary.important,
        [theme.breakpoints.up('sm')]: {
            margin: 'auto',
        },
    },
    buttonImportant: {
        marginTop: theme.spacing(6),
        marginBottom: theme.spacing(2),
    },
});

class Register extends React.Component {
    state = {
        data: {
            firstname: '',
            lastname: '',
            email: '',
            password: '',
            checkNewsletter: false,
            checkCGU: false,
            adId : ''
        },
        errors: {
            email:null,
            password:null,
            firstname:null,
            lastname:null,
            checkCGU:null
        },
        loading: false,
        showPassword: false
    }

    validate = data => {
        const errors = {};
        if (!Validator.isEmail(data.email)) errors.email = "Email invalide";
        if (!!!data.password) errors.password = "Requis";
        if (!!!data.firstname) errors.firstname = "Requis";
        if (!!!data.lastname) errors.lastname = "Requis";
        if (!data.checkCGU) errors.checkCGU = "Requis";
        
        return errors;
    };
    
    componentDidMount() {
        this.setState({
            data: {...this.state.data, adId: localStorage.getItem('adId')},
        })
    }

    onRegister = e => {
        e.preventDefault();
        
        
        const errors = this.validate(this.state.data);

        this.setState({ errors: errors });
        console.log('adId')
        console.log(this.state.data)
        if (Object.keys(errors).length === 0) {

            this.props.registerUserRequest(this.state.data)

            if (this.state.data.checkNewsletter)
                this.props.subscribeToNewsletterRequest({ email: this.state.data.email })
        }

    };

    UNSAFE_componentWillReceiveProps(nextProps) {
        this.setState({
            errors: nextProps.errors,
            loading: nextProps.loading
        })
    }
    onChange = e =>
        this.setState({
            data: { ...this.state.data, [e.target.name]: e.target.value }
        });
    handleCheckBoxChange = name => event => {
        this.setState({ data: { ...this.state.data, [name]: event.target.checked } });
    };

    handleChangePasswordVisibility = prop => event => {
        this.setState({ [prop]: event.target.value });
    };

    handleClickShowPassword = () => {
        this.setState({ showPassword: !this.state.showPassword });
    };

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

        return (
            <div className={classes.container}>

                <form className={classes.form}>

                    <TextField
                        value={data.lastname}
                        onChange={this.onChange}
                        id="nom"
                        name="lastname"
                        label="Nom"
                        margin="normal"
                        variant="outlined"
                        required
                        error={!!errors.lastname}
                    />
                    <TextField
                        value={data.firstname}
                        onChange={this.onChange}
                        id="prenom"
                        name="firstname"
                        label="Prénom"
                        margin="normal"
                        variant="outlined"
                        required
                        error={!!errors.firstname}
                    />

                    <TextField
                        value={data.email}
                        onChange={this.onChange}
                        id="emailRegister"
                        name="email"
                        label="Email"
                        margin="normal"
                        type="email"
                        variant="outlined"
                        required
                        error={!!errors.email}
                        autoComplete="username email"
                    />


                    <TextField
                        className={clsx(classes.margin, classes.textField)}
                        label="Password"
                        name="password"
                        id="adornment-password"
                        variant="outlined"
                        margin="normal"
                        type={this.state.showPassword ? 'text' : 'password'}
                        value={this.state.password}
                        onChange={this.onChange}
                        error={!!errors.password}
                        InputProps={{
                            endAdornment: (
                                <InputAdornment position="end">
                                    <IconButton
                                        edge="end"
                                        aria-label="Toggle password visibility"
                                        onClick={this.handleClickShowPassword}
                                    >
                                        {this.state.showPassword ? <Visibility /> : <VisibilityOff />}
                                    </IconButton>
                                </InputAdornment>
                            ),
                        }}
                    />


                    <FormControlLabel
                        control={
                            <Checkbox
                                id="cypCheckboxNewsletter"
                                value={data.checkNewsletter}
                                onChange={this.handleCheckBoxChange('checkNewsletter')}
                            />
                        }
                        className={classes.checkbox}
                        label="Je souhaite recevoir la newsletter de Talents Tube"

                    />

                    <FormControlLabel
                        name="checkCGU"
                        className={!!errors.checkCGU ? classes.checkbox + ' ' + classes.checkboxError : classes.checkbox}
                        control={
                            <Checkbox
                                id="cypCheckboxRegister"
                                value={data.checkCGU}
                                onChange={this.handleCheckBoxChange('checkCGU')} required
                            />

                        }
                        label="Je déclare avoir pris connaissance et accepte les termes et les CGU *"
                        required
                    />
                    <Button type="submit" variant="contained" className={classes.button + ' ' + classes.buttonImportant + ' cypButtonRegister'} onClick={this.onRegister}>
                        S'inscrire
                    </Button>

                    {/* <Typography
                        paragraph={true}
                        align="center"
                        className={classes.conditionalText}
                    >Ou</Typography> */}

                </form>

                {/* <SocialButtonsAuth linkedInAuth={this.props.linkedInAuth} facebookAuth={this.props.facebookAuth} /> */}

                <div classes={classes.form}>
                    <Typography
                        paragraph={true}
                        align="center"
                        className={classes.formText}
                    >Je possède un compte Talents Tube ?
                         <Link href={"/Login"} >
                            <span className={classes.formLink}>
                                Se connecter
                            </span>
                        </Link>
                    </Typography>
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        loading: !!state.user.loading,
        errors: !!state.user.errors ?state.user.errors: {
            email:null,
            password:null,
            firstname:null,
            lastname:null,
            checkCGU:null
        }
    };
}

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