import { FormEvent, useContext, useState } from "react";
import { useNavigate } from "react-router";
import { currentUser, login, LoginRequest, User } from "./api";

export interface LoginProps {
  onLogin: (user: User) => void;
}

export const Login = ({ onLogin }: LoginProps) => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<unknown>(null);
  const [loading, setLoading] = useState(false);

  async function doLogin() {
    setLoading(true);
    setError(null);
    const timeout = new Promise((r) => setTimeout(r, 1500));
    let user: User;
    try {
      login({ username, password });
      user = await currentUser();
    } catch (e) {
      await timeout;
      setError(e);
      setLoading(false);
      return
    }

    await timeout;
    onLogin(user);
  }

  function handleClick() {
    doLogin();
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    doLogin();
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <input type="text" id="username" name="username" placeholder="username" required value={username} onChange={evt => setUsername(evt.target.value)} />
      </div>
      <div>
        <input type="password" id="password" name="password" placeholder="password" minLength={8} value={password} required onChange={evt => setPassword(evt.target.value)} />
      </div>
      <button type="submit" value="login" style={{ fontSize: "small" }} onClick={handleClick} >login</button>
      {loading && <span className="loader" />}
    </form>
  )
}

/*
export default function Login(props: { onLogin: (user: User) => void }) {
  const { onLogin } = props;
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  async function handleLogin(e: FormEvent) {
    e.preventDefault()
    const timeout = new Promise((r) => setTimeout(r, 1500));
    let user: User;
    try {
      login({ username, password })
      user = await currentUser()
    } catch (e) { await timeout; return }
    await timeout;
    onLogin(user);
  }

  return <div>
    <form onSubmit={handleLogin}>
      <div>
        <input type="text" id="username" name="username" placeholder="username" required value={username} onChange={evt => setUsername(evt.target.value)} />
      </div>
      <div>
        <input type="password" id="password" name="password" placeholder="password" minLength={8} value={password} required onChange={evt => setPassword(evt.target.value)} />
      </div>
      <input className="button" type="submit" value="login" onSubmit={handleLogin} />
    </form>
  </div>
} */
