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

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

  async function login(formData: FormData) {
    let username = formData.get("username");
    let password = formData.get("password");
    let email = formData.get("email");
    let [_, status] = await client.POST("/register", {
      body: {
        username: username as string,
        password: password as string,
        email: email as string,
      },
    });
    if (status === 200) {
      navigator("/");
    } else {
      setError(true);
    }
  }

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