"use client";

import { useActionState } from "react";
import { login, register } from "@/app/actions/auth";

export default function AuthForm({ isRegister = false }: { isRegister?: boolean }) {
  const [state, formAction] = useActionState(isRegister ? register : login, null);

  return (
    <div className="w-full">
      <h1 className="font-bold mb-2">{isRegister ? "Register" : "Login"}</h1>
      <form className="flex flex-col gap-2" action={formAction}>
        <input name="username" className="p-2 bg-neutral-800 focus:outline-none focus:bg-neutral-700" placeholder="Username" required />
        <input name="password" className="p-2 bg-neutral-800 focus:outline-none focus:bg-neutral-700" placeholder="Password" type="password" required />
        {isRegister && (
          <input name="password_confirm" className="p-2 bg-neutral-800 focus:outline-none focus:bg-neutral-700" placeholder="Confirm password" type="password" required />
        )}
        <button type="submit" className="p-2 bg-neutral-800 hover:bg-neutral-700 cursor-pointer">
          {isRegister ? "Register" : "Login"}
        </button>
        {state?.error && <p>{state.error}</p>}
      </form>
    </div>
  );
}
