import React from 'react';
import './LoginForm.css';

import {supabase} from './api';
import {User} from '@supabase/supabase-js';

interface LoginFormProps {
  setUser: React.Dispatch<React.SetStateAction<User | undefined>>;
}

const LoginForm:React.FC<LoginFormProps> = ({setUser}) => {
  const [error, setError] = React.useState<string|undefined>();
  const [submitting, setSubmitting] = React.useState<boolean>(false);
  const [login, setLogin] = React.useState<string>("");
  const [password, setPassword] = React.useState<string>("");

  return (
    <form
      className="form-login"
      onSubmit={async e => {
        e.preventDefault();
        if(login) {
          setSubmitting(true); 
          setError(undefined);
          const {data, error: loginError} = await supabase.auth.signInWithPassword({
            email: login,
            password
          });
          setSubmitting(false)
          if(loginError) {
            setError(loginError.message || "Error authenticating");
            console.error(loginError);
            return;
          }
          if(data.user) {
            setUser(data.user);
          }
        }
      }}
    >
      <label>
        User:
        <input onChange={e => setLogin(e.target.value)} name="user" minLength={2} required/>
      </label>
      <label>
        Password:
        <input name="password" onChange={e =>  setPassword(e.target.value)}type="password" minLength={8} required/>
      </label>
      <div className="errors">{error && error}</div>
      <div className="button-row">
        <button disabled={!login || !password || !!submitting} type="submit">Let's Go!</button>
      </div>
    </form>
  );
};

export default LoginForm;
