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">E-mail</label>
      <input id="email" type="email" required />
      <br />
      <label htmlFor="password">Password</label>
      <input id="password" type="password" required />
      <br />
      <button type="submit">Login</button>
      <button onClick={() => setIsLogin( false )}>Register a new account</button>
    </form>
  }

  return (
    <form onSubmit={handleRegistration}>
      <label htmlFor="username">Username</label>
      <input id="username" type="text" required />
      <br />
      <label htmlFor="email">E-mail</label>
      <input id="email" type="email" required />
      <br />
      <label htmlFor="password">Password</label>
      <input id="password" type="password" required />
      <br />
      <label htmlFor="password2">Repeat password</label>
      <input id="password2" type="password" required />
      <br />
      <button type="submit">Register</button>
      <button onClick={() => setIsLogin( true )}>Login instead</button>
    </form>
  );
};