/*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, useState, useEffect } from 'react';
import styled from 'styled-components';
import FormInput from "../Components/FormInput.js"
import axios from 'axios'
import {apiUrl} from '../env';




const Button = styled.button`

  background-color: #00acc1;
  color:#fff;
  font-family: Roboto,sans-serif;
  font-size: 14px;
  font-weight: 500;
  height: 36px;
  border-radius: 3px;
  padding-left: 16px;
  padding-right: 16px;
  box-shadow: 0 2px 5px 0 rgba(0,0,0,.26);
  outline: none;
  position: relative;
  cursor: pointer;
  min-height: 36px;
  min-width: 88px;
  line-height: 36px;
  vertical-align: middle;
  align-items: center;
  text-align: center;
  border-radius: 3px;
  box-sizing: border-box;
  user-select: none;
  border: 0;
  padding: 0 6px;
  padding-right: 6px;
  padding-left: 6px;
  margin: 6px 8px;

  white-space: nowrap;
  text-transform: uppercase;
  font-weight: 500;
  font-size: 14px;
  font-style: inherit;
  font-variant: inherit;
  font-family: inherit;
  text-decoration: none;
  overflow: hidden;
  transition: box-shadow .4s cubic-bezier(.25,.8,.25,1),background-color .4s cubic-bezier(.25,.8,.25,1);


`



  function validateNome (nome) {
      let flag = false
      if(nome.length === 0) {
          flag = true
      }

      return flag
  }


  function validateMensagem (mensagem) {
      let flag = false
      if(mensagem.length === 0) {
          flag = true
      }

      return flag
  }

  function validateEmail (email) {
    let flag = false
    if (email.split("").filter(x => x === "@").length !== 1 || email.length < 7) {
      flag = true
    }
    return flag
  }

  function Formulario (props){

    const [nome, handleNome] = useState(
      {
        dict : {
         key:false,
         value:""
       }
     })
    const [email, handleEmail] = useState(
      {
        dict : {
         key:false,
         value:""
     }
    })
    const [mensagem, handleMensagem] = useState(
      {
        dict : {
         key: false,
         value:""
       }
      })


  const preencheNome = (e) => {
    const aux2 = e.target.value
    const flag = validateNome(aux2)
    handleNome({...nome, dict : {
      key : flag,
      value : e.target.value
    }})
    console.log(nome)
  }

  const preencheEmail = (e) => {
    const aux = e.target.value
    const flag = validateEmail(aux)
    handleEmail({...email, dict : {
      key : flag,
      value : e.target.value
    }})
    console.log(email)
  }

  const preencheMensagem = (e) => {
    const msg = e.target.value
    console.log(msg)
    let flag = validateMensagem(msg)
    handleMensagem({...mensagem, dict : {
      key : flag,
      value : msg
    }})
    console.log(mensagem)
  }

  const limpaTudo = () => {

    handleNome({
      dict : {
       key: false,
       value:""
     }}
   );

    handleEmail({
      dict : {
       key: false,
       value:""
     }}
    )

    handleMensagem({
      dict : {
       key: false,
       value:""
     }}
    )

  }



  const onSubmit = (e) => {
      //on submit we should prevent the page from refreshing
      e.preventDefault(); //though this is arguable
      console.log(!(nome.dict.key && email.dict.key && mensagem.dict.key ))
      // Se não houver erro em nunhum dos campos E nenhum dos campos for vazio: a página faz o contato com o backend e os campos ficam em branco no formulário
      if (!(nome.dict.key || email.dict.key || mensagem.dict.key )) {

        axios.post(`${apiUrl}/contacts`,
            {
              contact : {
                name: nome.dict.value,
                email: email.dict.value,
                message: mensagem.dict.value
              }

        }
        ).then()



        limpaTudo();

      }



  }




  return(



      <form onSubmit={e => onSubmit(e)}>
        <FormInput
          inputType={"text"}
          name={"nome"}
          value={nome.dict.value}
          placeholder={"Nome *"}
          error = {nome.dict.key}
          help = {nome.dict.key ? "insira seu nome para o contato " : ""}
          handleChange={e => preencheNome(e)}
        />
        <br/>
        <FormInput
          inputType={"text"}
          name={"email"}
          value={email.dict.value}
          placeholder={"E-mail *"}
          error = {email.dict.key}
          help = {email.dict.key ? "Formato de e-mail incorreto ou vazio, tente : usuario@provedor.com" : ""}
          handleChange={e => preencheEmail(e)}
        />
        <br/>
        <br/>
        <FormInput
          inputType={"text"}
          name={"mensagem"}
          value={mensagem.dict.value}
          placeholder={"Mensagem *"}
          multi = {true}
          rows = "5"
          rowsMax = "6"
          error = {mensagem.dict.key}
          help = {mensagem.dict.key ? "Faltou escrever sua mensagem de sugestão, crítica ou dúvida." : "Escreva sua mensagem no campo acima."}
          handleChange={e => preencheMensagem(e)}
        />
        <br/>
        <br/>
        <div style={{display: "flex", justifyContent: "center"}}>
          <Button onClick={e => onSubmit(e)} >ENVIAR MENSAGEM</Button>
        </div>
      </form>



  );
}

export default Formulario;