text: import React, { useState, useMemo } from 'react';
  
  import api from '../../../services/api';
  
  import './index.scss';
  import logo from '../../../assets/png/logo.png';
  
  import camera from '../../../assets/svg/camera.svg';
  
  import { faArrowCircleLeft, faChevronRight } from "@fortawesome/free-solid-svg-icons";
  import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
  
  export default function MentorForm(props) {
    const role = props.location.state.role;
    const { history } = props;
    
    const techs = props.location.state.techs;
    
    function Options({ options }) {
      return (
        options.map(option => 
          <option key={option._id} id={option._id} value={option.description}>
            {option.description}
          </option>
        )
      );
    }
  
    function removeItem(skill_id){
      const ul = document.getElementById("dynamic-list");
  
      let node = null;
      
      ul.childNodes.forEach((item) => {
        if(item.id === skill_id) {
          node = item;
        }
      });
  
      ul.removeChild(node);
    }
  
    function addItem() {
      const tech = {
        id: document.getElementById("techs").selectedOptions[0].id,
        name: document.getElementById("techs").value,
        price: document.getElementById("price").value
      }
  
      const ul = document.getElementById("dynamic-list");
      
      let onList = false;
  
      ul.childNodes.forEach((item) => {
        if(item.id === tech.id) {
          onList = true;
        }
      })
  
      const reg = /^\d+$/;
  
      if(!onList && reg.test(tech.price)) {
        var li = document.createElement("li");
        li.setAttribute('id',tech.id);
        li.appendChild(document.createTextNode(tech.name));
        li.appendChild(document.createTextNode(": R$"));
        li.appendChild(document.createTextNode(tech.price));
        li.appendChild(document.createTextNode(" /hora"));
        li.onclick = () => removeItem(tech.id);
        ul.appendChild(li);
      }
    }
  
    const availableOn = [];
  
    function addDays(day, isChecked) {
      if(isChecked) {
        availableOn.push(day);
      }
      else {
        const index = availableOn.indexOf(day);
        if (index !== -1) availableOn.splice(index, 1);
      }
    }
  
    const [name, setName] = useState('');
    const [birthdate, setBirthdate] = useState('');
    const [address, setAddress] = useState('');
    const [cpf, setCPF] = useState('');
    const [email, setEmail] = useState(props.location.state.email);
    const [emailConfirm, setEmailConfirm] = useState('');
    const [password, setPassword] = useState('');
    const [passwordConfirm, setPasswordConfirm] = useState('');
    const [bio, setBio] = useState('');
    const [avatar, setAvatar] = useState(null);
  
    const preview = useMemo(() => {
      return avatar ? URL.createObjectURL(avatar) : null
    }, [avatar]);
  
    let submit = false;
  
    async function handleSubmit(event) {
      event.preventDefault();
  
      if(email !== emailConfirm) {
        alert("Email e confirmação não coincidem");
      }
      else if(password !== passwordConfirm) {
        alert("Senha e confirmação não coincidem");
      }
      else {
        submit = true;
      }
  
      let skills = [];
  
      document.getElementById("dynamic-list").childNodes.forEach((item) => {
        skills.push(item.id + "," + item.childNodes[2].nodeValue);
      });
          
      skills = skills.join(";");
  
      if(submit) {
        const data = new FormData();
  
        data.append('name', name);
        data.append('birthdate', birthdate);
        data.append('address', address);
        data.append('cpf', cpf);
        data.append('email', email);
        data.append('password', password);
        data.append('description', bio);
        data.append('avatar', avatar);
        data.append('role', role);
        data.append('skills', skills);
        data.append('availableOn', availableOn);
  
        try {
          const response = await api.post('/mentors', data);
          const url = '/signup/mentors/' + response.data._id + '/confirmation';
  
          history.push(url, { 
            mentor: response.data
          })
        }
        catch(err) {
          console.log(err);
        }
      }
    }
  
    return (
      <div id="mentorSignUpFormScreen" className="container">
        <header className="header">
          <div id="firstRow" className="row">
            <section className="closeButton"/>
            
            <section className="logo">
              <img src={logo} alt=""/>
            </section>
            
            <section className="closeButton">
              <a href="/">
                <FontAwesomeIcon icon={faArrowCircleLeft} />
              </a>
            </section>
          </div>
          
          <div id="secondRow" className="row">
            <h1>
              Seja um de nossos incríveis mentores
            </h1>
          </div>
        </header>
        
        <form id="signUpForm" className="row" onSubmit={ handleSubmit }>
          <section className="data">
            <fieldset id="personalData">
              <legend>Dados pessoais</legend>
              
              <div className="formRow">
                <div className="input" data-placeholder="Digite seu nome completo">
                  <input
                  id="name"
                  type="text"
                  value = {name}
                  onChange= {
                    event => setName(event.target.value)
                  }
                  placeholder="Ciclano da Silva"
                  required
                  autoFocus
                  />
                </div>
                
                <div className="input" data-placeholder="Digite sua data de nascimento">
                  <input
                  id="birthdate"
                  type="date"
                  value={ birthdate }
                  onChange= {
                    event => setBirthdate(event.target.value)
                  }
                  placeholder="DD/MM/AAAA"
                  required
                  />
                </div>
              </div>
              
              <div className="formRow">
                <div className="input" data-placeholder="Digite seu endereço">
                  <input
                  id="address"
                  type="text"
                  value = {address}
                  onChange= {
                    event => setAddress(event.target.value)
                  }
                  placeholder="São Paulo, SP"
                  required
                  />
                </div>
                
                <div className="input" data-placeholder="Digite seu CPF">
                  <input
                  id="cpf"
                  type="text"
                  value={cpf}
                  onChange= {
                    event => setCPF(event.target.value)
                  }
                  placeholder="Digite somente números"
                  required
                  />
                </div>
              </div>
              
              <div className="formRow">
                <div className="input" data-placeholder="Digite seu melhor email">
                  <input
                  id="email"
                  type="email"
                  value = {email}
                  onChange= {
                    event => setEmail(event.target.value)
                  }
                  placeholder="ciclano@incrivel.com"
                  required
                  />
                </div>
                
                <div className="input" data-placeholder="Repita seu email">
                  <input
                  id="emailConfirm"
                  type="email"
                  value = {emailConfirm}
                  onChange= {
                    event => setEmailConfirm(event.target.value)
                  }
                  placeholder="ciclano@incrivel.com"
                  required
                  />
                </div>
              </div>
              
              <div className="formRow">
                <div className="input" data-placeholder="Digite uma senha">
                  <input
                  id="password"
                  type="password"
                  value = {password}
                  onChange= {
                    event => setPassword(event.target.value)
                  }
                  placeholder="Não contaremos sua senha a ninguém!"
                  required
                  />
                </div>
                
                <div className="input" data-placeholder="Repita sua senha">
                  <input
                  id="passwordConfirm"
                  type="password"
                  value = {passwordConfirm}
                  onChange= {
                    event => setPasswordConfirm(event.target.value)
                  }
                  placeholder="Não contaremos sua senha a ninguém!"
                  required
                  />
                </div>
              </div>
              
              <div className="formRow">
                <div className="textarea" data-placeholder="Escreva aqui uma boa descrição de seus interesses e paixões">
                  <textarea
                  id="bio"
                  value = {bio}
                  onChange= {
                    event => setBio(event.target.value)
                  }
                  rows="5"
                  placeholder="Essa é sua oportunidade de falar um pouco sobre você"
                  required
                  />
                </div>
              </div>
            </fieldset>
            
            <fieldset id="skills">
              <legend>Suas habilidades</legend>
  
              <div className="skillsSelector">
                <div className="select" data-placeholder="Valor por hora">
                  <div/>
                  <select name="techs" id="techs">
                    <Options options={techs} />
                  </select>
                </div>
                
                <div className="input" data-placeholder="Valor por hora">
                  <input
                  id="price"
                  type="text"
                  pattern="[0-9]*"
                  placeholder="Somente números"
                  required
                  />
                </div>
  
                <button type="button" onClick={addItem}>
                  Adicionar habilidade
                </button>
              </div>
              
              <div className="skillsListBox">
                <ul id="dynamic-list"/>
              </div>
            </fieldset>
  
            <fieldset id="availability">
              <legend>Disponibilidade</legend>
  
              <p>Selecione os dias preferenciais para atendimento</p>
  
              <div className="checkbox">
                <input
                  type="checkbox"
                  id="MONDAY"
                  name="MONDAY"
                  value="MONDAY"
                  onChange = {event => addDays(event.target.value, event.target.checked)}
                />
                <label htmlFor="MONDAY">
                  <span className="initial">
                    S
                  </span>
  
                  <span className="full">
                    Segunda
                  </span>
                </label>
  
                <input
                  type="checkbox" 
                  id="TUESDAY"
                  name="TUESDAY"
                  value="TUESDAY"
                  onChange = {event => addDays(event.target.value, event.target.checked)}
                />
                <label htmlFor="TUESDAY">
                  <span className="initial">
                    T
                  </span>
  
                  <span className="full">
                    Terça
                  </span>
                </label>
                
                <input
                  type="checkbox" 
                  id="WEDNESDAY"
                  name="WEDNESDAY"
                  value="WEDNESDAY"
                  onChange = {event => addDays(event.target.value, event.target.checked)}
                />
                <label htmlFor="WEDNESDAY">
                  <span className="initial">
                    Q
                  </span>
  
                  <span className="full">
                    Quarta
                  </span>
                </label>
                
                <input
                  type="checkbox" 
                  id="THURSDAY"
                  name="THURSDAY"
                  value="THURSDAY"
                  onChange = {event => addDays(event.target.value, event.target.checked)}
                />
                <label htmlFor="THURSDAY">
                  <span className="initial">
                    Q
                  </span>
  
                  <span className="full">
                    Quinta
                  </span>
                </label>
                
                <input
                  type="checkbox" 
                  id="FRIDAY"
                  name="FRIDAY"
                  value="FRIDAY"
                  onChange = {event => addDays(event.target.value, event.target.checked)}
                />
                <label htmlFor="FRIDAY">
                  <span className="initial">
                    S
                  </span>
  
                  <span className="full">
                    Sexta
                  </span>
                </label>
                
                <input
                  type="checkbox" 
                  id="SATURDAY"
                  name="SATURDAY"
                  value="SATURDAY"
                  onChange = {event => addDays(event.target.value, event.target.checked)}
                />
                <label htmlFor="SATURDAY">
                  <span className="initial">
                    S
                  </span>
  
                  <span className="full">
                    Sábado
                  </span>
                </label>
                
                <input
                  type="checkbox" 
                  id="SUNDAY"
                  name="SUNDAY"
                  value="SUNDAY"
                  onChange = {event => addDays(event.target.value, event.target.checked)}
                />
                <label htmlFor="SUNDAY">
                  <span className="initial">
                    D
                  </span>
  
                  <span className="full">
                    Domingo
                  </span>
                </label>
              </div>
            </fieldset>
  
            <div className="inputSubmit">
              <button 
                type="submit"
              >
                <span>Próximo passo</span>
                <FontAwesomeIcon icon={faChevronRight}/>
              </button>
            </div>                  
          </section>
          
          <section className="avatar">
            <label 
              id="label"
              style={{
                backgroundImage:`url(${preview})`,
              }}
              className={avatar ? 'has-avatar' : '' }  
            >
              <img src={camera} alt="Selecione uma imagem"/>
              <input 
                type="file"
                accept="image/*"
                onChange={
                  event => setAvatar(event.target.files[0])
                }
                required
              />
            </label>
  
            <span>
              Selecione uma imagem para usar como foto de perfil no formato .PNG ou .JPEG
            </span>
          </section>       
        </form>
      </div>
    );
  }
  