/*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, {useState} 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'
import {apiUrl} from '../env.js'
import {GoogleLoginButton} from './LoginContainerFunction'
import ValidateUserInput from '../Components/FormValidationFunction.js'
import GoogleLogo from "../img/logo_google.svg"

var Recaptcha = require('react-recaptcha')

async function handleGoogleAttempt () {
	console.log("handleGoogleAttempt")
	let request_url = (
        `${apiUrl}/omniauth/google_oauth2?auth_origin_url=` + window.location.href + '&omniauth_window_type=sameWindow&resource_class=User'
    )
    window.location.replace(request_url)
}
export default function SignUpContainer (props) {
    const [formNome, setNome] = useState(
        {
                key : false,
                value : "",
        }
    )

    const [formEmail, setEmail] = useState(
        {
                key : false,
                value : "",
        }
    )

    const [formSenha, setSenha] = useState(
        {
                key : false,
                value : ""
        }
    )

    const handleChange = (e, type) => {
        const userInput = e.target.value
        const flag = ValidateUserInput(type, userInput)

        if (type === 'username') {
            setNome({...formNome,
                key : flag,
                value : userInput
            })
            console.log(formNome)
        }
        else if(type === 'email') {
            setEmail({...formEmail,
                key : flag,
                value : userInput
            })
            console.log(formEmail)
        }
        else if(type === 'password') {
            setSenha({...formSenha,
                key : flag,
                value : userInput
            })
            console.log(formSenha)
        }
    }

    const limpaCamposForm = () => {
        setNome({...formNome,
            key : false,
            value : ''
        })

        setEmail({...formEmail,
            key : false,
            value : ''
        });

        setSenha({...formSenha,
            key : false,
            value : ''
        })
    }

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

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

    const onSubmit = (e) => {
        e.preventDefault();
        const newLogin = {name : formNome.value, email : formEmail.value, password : formSenha.value}

        if (!(formNome.key || formEmail.key || formSenha.key)) {
            props.handleLoginInfo(newLogin)
            limpaCamposForm()
        }
    }

    return (
        <ContainerStyled >
            <DialogHeaderStyled>
                <span style={{width:"32px"}}/>
                <H2Styled> Cadastrar-se
                </H2Styled>
                <StyledCloseModalButton onClick={props.handleClose} >
                    <CloseIcon />
                </StyledCloseModalButton>
            </DialogHeaderStyled>

            <DialogContentDiv>
                <SocialConnectDiv>
                        <GoogleLoginButton onClick={handleGoogleAttempt}>
                            <img src={GoogleLogo} alt="google-logo" className="google-logo"/>
                            <span>Usando o Google</span>
                        </GoogleLoginButton>
                </SocialConnectDiv>

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

                <form onSubmit={onSubmit}>
                    <FormInput
                        inputType={"text"}
                        name={"name"}
                        value={formNome.value}
                        placeholder={"Nome Completo"}
                        handleChange={e => handleChange(e, 'username')}
                        required={true}
                        error={formNome.key}
                    />
                    <br/>
                    <FormInput
                        inputType={"text"}
                        name={"email"}
                        value={formEmail.value}
                        placeholder={"E-mail"}
                        handleChange={e => handleChange(e, 'email')}
                        required={true}
                        error={formEmail.key}
                        help = {formEmail.key ? (formEmail.value.length == 0 ? "Faltou preencher seu e-mail." : <span>Insira um endereço de e-mail válido.<br/>Por exemplo: seunome@gmail.com, seunome@hotmail.com</span>) : ""}
                        />
                    <br/>
                    <FormInput
                        inputType={"password"}
                        name={"password"}
                        value={formSenha.value}
                        placeholder={"Senha"}
                        handleChange={e => handleChange(e, 'password')}
                        required={true}
                        error={formSenha.key}
                        help = {formSenha.key ? (formSenha.value.length == 0 ? "Faltou digitar sua senha." : "A senha precisa ter no mínimo 8 caracteres.") : ""}
                        />
                    <br/>
                    <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 => switchModal(e)}>ENTRAR</StyledAnchor></span>
                </DialogFooterStyled>
            </DialogContentDiv>
        </ContainerStyled>
    )
}

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%;
        min-width : unset !important;

    }
`

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 : 44%;
`

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

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;
`