"use client";

import { useActionState } from "react";
import { registerUser } from "@/lib/actions/auth";

export function RegisterForm() {
  const [state, formAction, isPending] = useActionState(
    registerUser,
    undefined,
  );

  return (
    <form action={formAction} className="mt-8 flex flex-col gap-4">
      {state?.error && (
        <p className="rounded bg-terracotta/10 px-4 py-2 text-sm text-terracotta">
          {state.error}
        </p>
      )}

      {/* Honeypot: hidden from real users, bots tend to fill every field */}
      <label className="absolute -left-[9999px]" aria-hidden="true">
        Leave this field blank
        <input
          type="text"
          name="website"
          tabIndex={-1}
          autoComplete="off"
        />
      </label>

      <label className="flex flex-col gap-1">
        <span className="text-sm font-medium text-charcoal">Username</span>
        <input
          type="text"
          name="username"
          required
          pattern="[a-zA-Z0-9_]+"
          title="Letters, numbers, and underscores only"
          className="rounded border border-charcoal/20 bg-warm-white px-4 py-2 text-charcoal"
        />
      </label>

      <label className="flex flex-col gap-1">
        <span className="text-sm font-medium text-charcoal">Email</span>
        <input
          type="email"
          name="email"
          required
          className="rounded border border-charcoal/20 bg-warm-white px-4 py-2 text-charcoal"
        />
      </label>

      <label className="flex flex-col gap-1">
        <span className="text-sm font-medium text-charcoal">Password</span>
        <input
          type="password"
          name="password"
          required
          minLength={8}
          className="rounded border border-charcoal/20 bg-warm-white px-4 py-2 text-charcoal"
        />
      </label>

      <button
        type="submit"
        disabled={isPending}
        className="mt-2 rounded-full bg-terracotta px-6 py-2 font-medium text-white hover:bg-terracotta/90 disabled:opacity-60"
      >
        {isPending ? "Creating account..." : "Register"}
      </button>
    </form>
  );
}
