import { useState } from "react";
import { useNavigate } from "react-router";
import client from "~/api/client";
import { useUserStore } from "~/hooks/user";

export default function LoginPage() {
  const user = useUserStore((state) => state.user);
  const setUser = useUserStore((state) => state.setUser);
  const [error, setError] = useState(false);
  const navigator = useNavigate();

  async function login(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    let username = formData.get("username");
    let password = formData.get("password");
    let [newUser, status] = await client.POST("/login", {
      body: {
        username: username as string,
        password: password as string,
      },
    });
    if (status === 200) {
      setUser(newUser);
      navigator("/");
    } else {
      setError(true);
    }
  }

  return (
    <div>
      {user !== null ? (
        <h1>You are already logged in.</h1>
      ) : (
        <>
          <h1>Login</h1>
          {error && (
            <h2 style={{ color: "red" }}>
              An error occurred. Please try again.
            </h2>
          )}
          <form onSubmit={login}>
            <label>
              Username:
              <input type="text" name="username" />
            </label>
            <label>
              Password:
              <input type="password" name="password" />
            </label>
            <button type="submit">Login</button>
          </form>
        </>
      )}
    </div>
  );
}
