import React, { useState } from 'react';
import { Accounts } from 'meteor/accounts-base';
import { useNavigate } from 'react-router-dom';
import { Meteor } from 'meteor/meteor';


export const Login = () => {
  const [isLogin, setIsLogin] = useState( { initialState: true } );
  const navigate = useNavigate();

  const handleLogin = (e) => {
    e.preventDefault();
    // console.dir(e);
    // console.dir(e.target.elements.email.value);
    // console.dir(e.target.elements.password.value);
    const email = e.target.elements.email.value;
    const password = e.target.elements.password.value;

    Meteor.loginWithPassword(email, password, (err) => {
      if (err) {
        console.error(err);
      } else {
        navigate('/');
      }
    });
  };

  const handleRegistration = (e) => {
    e.preventDefault();
    // console.dir(e);
    const username = e.target.elements.username.value;
    const email = e.target.elements.email.value;
    const password = e.target.elements.password.value;
    const password2 = e.target.elements.password2.value;

    if (password !== password2) {
      console.error("Passwords do not match!");
      return null;
    }

    Accounts.createUserAsync({
      username,
      email,
      password
    }).then(() => navigate('/'))
    
  };

  if (isLogin) {
    return <form onSubmit={handleLogin}>
      <label htmlFor="email">Correu electrònic o nom d'usuari: </label>
      <input id="email" type="email" required />
      <br />
      <label htmlFor="password">Contrasenya: </label>
      <input id="password" type="password" required />
      <br />
      <button type="submit">Entra</button>
      <button onClick={() => setIsLogin( false )}>Registra un compte nou</button>
    </form>
  }

  return (
    <form onSubmit={handleRegistration}>
      <label htmlFor="username">Nom d'usuari: </label>
      <input id="username" type="text" required />
      <br />
      <label htmlFor="email">Correu electrònic: </label>
      <input id="email" type="email" required />
      <br />
      <label htmlFor="password">Contrasenya: </label>
      <input id="password" type="password" required />
      <br />
      <label htmlFor="password2">Repeteix la contrasenya: </label>
      <input id="password2" type="password" required />
      <br />
      <label htmlFor="tel">Telèfon: </label>
      <input id="tel" type="tel" required />
      <br />
      <label htmlFor="codi">Codi d'entrada (opcional): </label>
      <input id="codi" type="text" />
      <br />
      <button type="submit">Registrar</button>
      <button onClick={() => setIsLogin( true )}>Torna per accedir</button>
    </form>
  );
};