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

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 = async (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;
    }

    const userId = await Accounts.createUserAsync({
      username,
      email,
      password
    });
    console.log("userId deL NOU USUARI: ", userId);
    userId && await Roles.addUsersToRolesAsync(userId, [ROLS_GLOBALS.USUARI]);
    navigate('/');

    return userId;
    
  };

  if (isLogin) {
    return <form
      onSubmit={handleLogin}
      style={{
        border: `2px solid #cccc`,
        padding: `.8rem`,
        borderRadius: `.5em`,
        display: `inline-block`,
        backgroundColor: `#eeed`
      }}
    >
      <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
      action={async d => {

        // let userId, codi;

        try {

          const username = d.get('username');
          const email = d.get('email');
          const tel = d.get('tel');
          const password = d.get('password');
          const password2 = d.get('password2');
          const codi = d.get('codi');

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

          console.log("username: ", username);
          console.log("email: ", email);
          console.log("tel: ", tel);
          console.log("password: ", password);
          console.log("password2: ", password2);
          console.log("codi: ", codi);

          const uObj = {
            username,
            email,
            tel,
            password,
            password2
          };

          Meteor.callAsync('creaUsuariAmbCodi', uObj, codi);

          // userId = await Accounts.createUser({
          //   username,
          //   email,
          //   password
          // });

          
        //   userId && await Roles.addUsersToRolesAsync(userId, [ROLS_GLOBALS.USUARI]);
          
        //   console.log("userId deL NOU USUARI: ", userId);

          

        } catch (err) {
          alert(err);
          console.error(err);
        }

        // try {
        //   userId && await Meteor.callAsync('usaCodiAmbUsuari', userId, codi);
        //   navigate('/');
        // } catch (err2) {
        //   alert(err2);
        //   console.error(err2);
        // }



          // Meteor.callAsync('editaOAfigCodi', {
          //       ...codiGenerat || [],
          //       codi: codiGenerat,
          //       ambit: d.get('selAmbit') || "",
          //       rol: d.get('selRol'),
          //       act_abs: d.get('activ_abs'),
          //       act_cond: d.get('activ_cond'),
          //       periode_validesa_ini: d.get('periode_validesa_ini'),
          //       periode_validesa_fi: d.get('periode_validesa_fi')
          // })
          //       .then(() => setAmbitSeleccionat(null))
          //       .catch(err => console.error(err))
          // ;
        
      }}

      style={{
        border: `2px solid #cccc`,
        padding: `.8rem`,
        borderRadius: `.5em`,
        display: `inline-block`,
        backgroundColor: `#eeed`
      }}
    >
      Avatar: <img
        style={{
          width: `3em`,
          height: `3em`,
          borderRadius: `50%`,
          overflow: `hidden`,
          verticalAlign: `middle`,
          margin: `.3em`,
          border: `solid 4px whitesmoke`
        }}
        // src={u?.profile?.avatarLink}

        onClick={ev => {
          
        }}
      />
      <br />
      <label htmlFor="username">Nom d'usuari: </label>
      <input id="username" name="username" type="text" required />
      <br />
      <label htmlFor="email">Correu electrònic: </label>
      <input id="email" name="email" type="email" required />
      <br />
      <label htmlFor="password">Contrasenya: </label>
      <input id="password" name="password" type="password" required />
      <br />
      <label htmlFor="password2">Repeteix la contrasenya: </label>
      <input id="password2" name="password2" type="password" required />
      <br />
      <label htmlFor="tel">Telèfon: </label>
      <input id="tel" name="tel" type="tel" required />
      <br />
      <label htmlFor="codi">Codi d'entrada (opcional): </label>
      <input id="codi" name="codi" type="text" style={{textAlign: `center`, fontWeight: `bolder`, fontSize: `1.1rem`}} onChange={ev => ev.target.value = (ev.currentTarget.value.length <= 5 && ev.currentTarget.value.toUpperCase()) || ev.currentTarget.value.slice(0, 5) } />
      <br />
      <button type="submit">Registrar</button>
      <button onClick={() => setIsLogin( true )}>Torna per accedir</button>
    </form>
  );
};