import React, { Fragment } from 'react';
import PropTypes from "prop-types";
import Layout from '../components/templates/Layout';
import { TextField, Button, Typography } from '@material-ui/core';
import SwipeableViews from 'react-swipeable-views';
import AppBar from '@material-ui/core/AppBar';
import Link from '@material-ui/core/Link';
import { withStyles } from '@material-ui/core/styles';
import Loader from './../components/templates/loader'
import { connect } from "react-redux";
import Validator from "validator";
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Router from 'next/router'
// import Register from '../components/organisms/Register';
import { requestLogin, requestOauthLogin, requestLoginFailure } from "../actions/auth";
import { makeStyles } from '@material-ui/core/styles';
import { amber, green } from '@material-ui/core/colors';
import _ from "lodash"
import Snack from '../components/atoms/snack'
import SocialButtonsAuth from '../components/atoms/SocialButtonsAuth';
import jssPluginPropsSort from 'jss-plugin-props-sort';
import Head from 'next/head'
import ReCAPTCHA from "react-google-recaptcha";
import getConfig from 'next/config'
const {publicRuntimeConfig} = getConfig()

function TabContainer({ children, dir }) {
    return (
        <Typography component="div" dir={dir} style={{ padding: 8 * 3 }}>
            {children}
        </Typography>
    );
}

TabContainer.propTypes = {
    children: PropTypes.node.isRequired,
    dir: PropTypes.string.isRequired,
};

const styles = theme => ({
    container: {
        display: 'flex',
        flexDirection: 'column',
    },
    AppBar: {
        position: 'fixed',
        top: theme.spacing(8),
    },
    tab: {
        '& span.MuiTab-wrapper': {
            fontSize: '1.1em',
            fontWeight: '600',
            textTransform: 'none',
        }
    },
    tabContainer: {
        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',
        cursor: 'pointer',
    },
    forgetPasswordText: {
        marginTop: theme.spacing(2),
    },
    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',
        },
    },
    link: {
        color: theme.palette.primary.dark,
        fontWeight: 400,
        fontSize: '0.9em',
    },
    input50: {
        width: '50%',
    },
    button: {
        textTransform: 'inherit',
        marginLeft: theme.spacing(8),
        marginRight: theme.spacing(8),
        marginTop: theme.spacing(4),
        marginBottom: theme.spacing(2),
        padding: theme.spacing(1.2, 2),
        borderRadius: '3px',
        color: theme.palette.secondary.main,
        backgroundColor: theme.palette.primary.important,
        [theme.breakpoints.up('sm')]: {
            margin: 'auto',
        },
    },
    buttonImportant: {
        marginTop: theme.spacing(6),
    },
});

const recaptchaRef = React.createRef();
class LoginPage extends React.Component {
    state = {
        data: {
            email: "",
            password: ""
        },
        errors: {},
        loading: false,
        tabIndex: 0,
        openSnack: false,
        redirection:""
    };

    static getInitialProps({ query }) {
        const { error, inscription } = query
        let err = null;
        if (!!error)
            err = { message: error };
        return { errors: err, openSnack: !!error, inscription };
    }

    UNSAFE_componentWillReceiveProps(nextProps) {
        if (!_.isEmpty(nextProps.errors))
            localStorage.removeItem("ttJWT");

        this.setState({
            errors: nextProps.errors,
            loading: nextProps.loading,
            openSnack: !_.isEmpty(nextProps.errors),
        })
        this.setState({
            tabIndex: (nextProps.inscription) ? 1 : 0,
        })
    }

    componentDidMount() {
        console.log("redirect login");
        console.log(localStorage.getItem('loginRedirect'));
        this.setState({
            tabIndex: (this.props.inscription) ? 1 : 0,
            redirection : localStorage.getItem('loginRedirect')
        })
    }

    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);
        recaptchaRef.current.execute();
        this.setState({ errors });
        if (Object.keys(errors).length === 0) {
            this.setState({ loading: true });
            this.props.requestLogin(this.state.data)
        }
    };

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

    validate = data => {
        const errors = {};
        if (!Validator.isEmail(data.email)) errors.email = "Invalid email";
        if (!data.password) errors.password = "Can't be blank";
        return errors;
    };

    linkedInAuth = () => {
        this.props.requestOauthLogin();
        Router.push('/auth/linkedin')
    }

    facebookAuth = () => {
        this.props.requestOauthLogin();
        Router.push('/auth/facebook')
    }

    handleChange = (event, newValue) => {
        this.setState({ tabIndex: newValue });
    }

    handleChangeIndex = (index) => {
        this.setState({ tabIndex: index });
    }

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

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

        return (
            <Layout>
                <Head>
                    <title key="title">Login</title>
                    <meta key="robots" name="robots" content="noindex, follow"></meta>
                </Head>
                <div className={classes.container}>
                    {/* {!!errors && (
                        <div className="alert alert-danger">{errors && errors.message}</div>
                    )} */}
                    {loading && (
                        <Loader />
                    )}
                    {!loading && (
                        <Fragment>
                            {/* <AppBar className={classes.AppBar} color="default">
                                <Tabs
                                    value={this.state.tabIndex}
                                    onChange={this.handleChange}
                                    indicatorColor="primary"
                                    variant="fullWidth"
                                >
                                    <Tab label="Connexion" className={classes.tab} />
                                    <Tab label="Inscription" className={classes.tab} />
                                </Tabs>
                            </AppBar> */}
                            <SwipeableViews
                                axis={'x'}
                                index={this.state.tabIndex}
                                onChangeIndex={() => this.handleChangeIndex()}
                            >
                                <TabContainer dir={'x'}>
                                    <div className={classes.tabContainer}>
                                        <form className={classes.form} onSubmit={this.onSubmit}>
                                            <TextField
                                                value={data.email}
                                                id="email"
                                                name="email"
                                                label="Email"
                                                margin="normal"
                                                type="email"
                                                value={data.email}
                                                onChange={this.onChange}
                                                autoComplete="username"
                                                variant="outlined"
                                                error={this.state.errors && !!this.state.errors.email}
                                                className={'cypInputEmail'}
                                                required

                                            />

                                            <TextField
                                                value={data.password}
                                                id="password"
                                                name="password"
                                                label="Mot de passe"
                                                margin="normal"
                                                type="password"
                                                value={data.password}
                                                onChange={this.onChange}
                                                autoComplete="current-password"
                                                variant="outlined"
                                                className={'cypInputPassword'}
                                                required
                                            />
                                            <Button type="submit" variant="contained" className={classes.button + ' ' + classes.buttonImportant + ' cypButtonConnexion'}>
                                                Se connecter
                                        </Button>
                                            <ReCAPTCHA
                                                id="component-outlined"
                                                ref={recaptchaRef}
                                                sitekey={publicRuntimeConfig.ReCAPTCHA.siteKey}
                                                size="invisible"
                                            />
                                            <Typography
                                                className={classes.forgetPasswordText}
                                                paragraph={true}
                                                align="center"
                                            >
                                                <Link href={"/ResetPassword"} className={classes.link}>
                                                    Mot de passe oublié ?
                                                    
                                                </Link>
                                                
                                            </Typography>


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


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

                                        <div className={classes.form}>
                                            <Typography
                                                paragraph={true}
                                                align="center"
                                                className={classes.formText}
                                            >Je ne possède pas de compte Talents Tube ?
                                        
                                                    <Link href="/Inscription">S'inscrire</Link>
                                        
                                            </Typography>

                                        </div>
                                        <div className={classes.form}>
                                            <Typography
                                                paragraph={true}
                                                align="center"
                                            >{this.state.openSnack}
                                            </Typography>
                                        </div>
                                    </div>

                                </TabContainer>
                                {/* <TabContainer dir={'x'}>
                                    <Register linkedInAuth={this.linkedInAuth} facebookAuth={this.facebookAuth} />
                                </TabContainer> */}
                            </SwipeableViews>
                        </Fragment>
                    )}
                </div>
                <Snack variant="error" message={!!!_.isEmpty(this.state.errors) && this.state.errors.message}
                    openSnack={this.state.openSnack} onClose={this.handleClose} />
            </Layout>
        );
    }
}

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



export default withStyles(styles)(connect(mapStateToProps, { requestLogin, requestOauthLogin, requestLoginFailure })(LoginPage));
