/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre
Departamento de Informatica - Universidade Federal do Parana

This file is part of Plataforma Integrada MEC.

Plataforma Integrada MEC is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Plataforma Integrada MEC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Plataforma Integrada MEC.  If not, see <http://www.gnu.org/licenses/>.*/

import React, {Component} from "react";
import GoogleLogin from 'react-google-login'
import { Button } from '@material-ui/core';
//import FacebookLogin from 'react-facebook-login';
import CloseIcon from '@material-ui/icons/Close';
import styled from 'styled-components'
import {device} from './device.js'
import FormInput from "./FormInput.js"
import {StyledCloseModalButton, DialogContentDiv, DialogHeaderStyled, SocialConnectDiv, StyledGoogleLoginButton, H3Div} from './LoginContainer.js'
const responseGoogle = (response) => {
  console.log(response);
}

const responseFacebook = (response) => {
  console.log(response);
}

var Recaptcha = require('react-recaptcha')

//alterar funcao do callback
var callback = function () {
  console.log('Done!!!!');
};

function validateUserInfo (name, email, password) {
    const errors = []

    if(name.lenght === 0 ) {
        errors.push({name : "name", msg : "Faltou preencher seu nome completo."})
    }
    if(email.length === 0) {
        errors.push({name : "email", msg : "Faltou preencher seu e-mail."})
    }
    else if ( (email.split("").filter(x => x === "@").length !== 1) || (email.indexOf(".") === -1) ){
        errors.push({name : "email", msg : "Insira um endereço de email válido."})
        errors.push({name : "email", msg : "Por exemplo: seunome@gmail.com, seunome@hotmail.com"})
    }
    if(password.length === 0) {
        errors.push({ name : "password", msg : "Faltou definir uma senha."})
    }

    return errors
}

class SignUpContainer extends Component {
    constructor (props) {
        super(props);

        this.state = {
            name: "",
            email: "",
            password: "",

            errors : []
        };
    };

    switchModal = (e) => {
        e.preventDefault()
        this.props.handleClose()
        this.props.openLogin()
    };

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

    };

    onSubmit = (e) => {
        //on submit we should prevent the page from refreshing
        e.preventDefault(); //though this is arguable
        const { name, email, password } = this.state;
        const errors = validateUserInfo(name, email, password)
        console.log(this.state)
        if ( errors.length < 1) {
            //pass user info to Store.js and clear all text fields
            this.props.handleLoginInfo(this.state)
            this.setState({
                name: "",
                email: "",
                password: ""
            })
        }
        else {
            this.setState({errors})
        }

    }

    render () {
        const { errors } = this.state;
        return (
            <ContainerStyled >
                <DialogHeaderStyled>
                    <span style={{width:"32px"}}/>
                    <H2Styled> Cadastrar-se
                    </H2Styled>
                    <StyledCloseModalButton onClick={this.props.handleClose} >
                        <CloseIcon />
                    </StyledCloseModalButton>
                </DialogHeaderStyled>

                <DialogContentDiv>
                    <SocialConnectDiv>
                        <StyledGoogleLoginButton
                            clientId="658977310896-knrl3gka66fldh83dao2rhgbblmd4un9.apps.googleusercontent.com"
                            onSuccess={responseGoogle}
                            onFailure={responseGoogle}
                            cookiePolicy={'single_host_origin'}
                        >
                            <span style={{textTransform:"none", fontSize:"13px"}}>Usando o Google</span>
                        </StyledGoogleLoginButton>
                    </SocialConnectDiv>

                <H3Div>
                    <H3Styled>
                        <RightSideStrikedH3/>
                        <span style={{verticalAlign:"middle"}}>ou</span>
                        <LeftSideStrikedH3/>
                    </H3Styled>
                </H3Div>

                <form ref="form" onSubmit={this.onSubmit}>
                {errors.map(error => (
                    <p key={error.name}>Error: {error.msg}</p>
                ))}
                    <FormInput
                        inputType={"text"}
                        name={"name"}
                        value={this.state.name}
                        placeholder={"Nome Completo"}
                        handleChange={e => this.handleChange(e)}
                        required={true}
                    />
                    <br/>
                    <FormInput
                        inputType={"text"}
                        name={"email"}
                        value={this.state.email}
                        placeholder={"E-mail"}
                        handleChange={e => this.handleChange(e)}
                        required={true}
                        />
                    <br/>
                    <FormInput
                        inputType={"password"}
                        name={"password"}
                        value={this.state.password}
                        placeholder={"Senha"}
                        handleChange={e => this.handleChange(e)}
                        required={true}
                        />
                    <br/>
                    <Recaptcha
                        sitekey="6LcyFr8UAAAAAOd0Po6rmZC1D_nYik8nLCAkNKsc"
                        size="normal"
                        render="explicit"
                        onloadCallback={callback}
                    />
                    <ConfirmContainerStyled>
                        <StyledSignUpButton type="submit" variant="contained">
                            <span
                                style={{paddingLeft:"16px", paddingRight:"16px", borderRadius:"3px", boxSizing:"border-box",
                                    fontFamily:"Roboto, sans serif", fontWeight:"500", color:"#fff"}}
                            >
                                CADASTRAR
                            </span>
                        </StyledSignUpButton>
                    </ConfirmContainerStyled>
                </form>

                <TermosDeUsoStyled>
                    <p>Ao se cadastrar, você está aceitando os Termos de Uso e de Política
                    de Privacidade. <a href="./">Ler Termos</a>.</p>
                </TermosDeUsoStyled>

                <DialogFooterStyled>
                    <span style={{textAlign:"center", fontSize: "14px"}}>Já possui cadastro? <StyledAnchor href="" onClick={e => this.switchModal(e)}>ENTRAR</StyledAnchor></span>
                </DialogFooterStyled>
                </DialogContentDiv>
            </ContainerStyled>
        )
    }
}

export default SignUpContainer

const ContainerStyled = styled.div`
    box-sizing : border-box;
    background-color : white;
    max-width : none;
    align : center;
    display : flex;
    flex-direction : column;
    min-width : 450px;

    max-height : none;
    position : relative;
    padding : 10px;
    @media ${device.mobileM} {
        width : 100%;
        height : 100%;
    }
`

const DialogFooterStyled = styled.div`
    box-sizing : border-box;
    font-family : 'Roboto', sans serif;
    margin : 20px -20px;
    padding-top : 20px;
    border-top : 1px #e5e5e5 solid;
    justify-content : center;
    text-align : center;
    line-height : 1.42857143
`

const TermosDeUsoStyled = styled.div`
    font-family: 'Roboto', sans serif, 'Helvetica Neue', Helvetica, Arial, sans-serif;
    color : #666;
    font-size : 13px;
    margin : 0 0 10px;
    max-width : 350px;
    margin-top : 10px;
    text-align : start;
`

const H2Styled = styled.h2`
    align-self : center;
    color : #666;
    font-size : 26px;
    font-weight : lighter;
    justify-content: space-between;
    font-family: 'Roboto', sans serif, 'Helvetica Neue', Helvetica, Arial, sans-serif !important;
    text-align: center;
    letter-spacing: .005em;
`

const H3Styled = styled.h3`
    overflow : hidden;
    text-align : center;
    font-size : 14px;
    color : #666;
    margin : 10px 0;
`
const RightSideStrikedH3 = styled.div`
    display :  inline-block;
    border-bottom: 1px dotted #666;
    vertical-align :  middle;
    font-weight : 500;
    margin-right : 5px;
    width : 45%;
`

const LeftSideStrikedH3 = styled.div`
    display :  inline-block;
    border-bottom: 1px dotted #666;
    vertical-align :  middle;
    font-weight : 500;
    margin-left : 5px;
    width : 45%;
`

const StyledAnchor = styled.a`
    color : #00bcd4;
    text-decoration : none;
`
//const StyledCloseModalButton = styled(Button)`
//    display : inline-block;
//    position : relative;
//    float : right !important;
//    margin-right : -8px;
//    background : transparent;
//    min-width: 0 !important;
//    width : 40px;
//`

const ConfirmContainerStyled = styled.div`
    display :  flex;
    margin-top : 10px;
    align-items : center;
    justify-content : center;
    box-sizing : border-box;
    font-size : 13px;
`

const StyledSignUpButton = styled(Button)`
    background-color: #00bcd4 !important;
    box-shadow : none !important;
    outline: none !important;
    border : 0 !important;
    overflow : hidden !important;
    width : 50% !important;
    display : inline-block !important;
    font-family : 'Roboto', sans serif !important;
    font-size: 14px !important;
    height : 36px !important;
    align-items : center !important;
    border-radius: 3px !important;
    align-self : 50% !important;
    :hover {
        background-color : #00acc1 !important;
    }
`

const StyledRecaptcha = styled(Recaptcha)`
    display : flex !important;
    justify-content : center !important;
`