import Link from "next/link";
import { registerUser } from "@/lib/user-actions";
import { hasAdminUser } from "@/lib/setup";
import { getAppSettings } from "@/lib/settings";
import { redirect } from "next/navigation";

export const dynamic = "force-dynamic";

export default async function RegisterPage({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
  if (!(await hasAdminUser())) {
    redirect("/setup");
  }
  const settings = await getAppSettings();
  if (settings.registrationMode === "DISABLED") {
    redirect("/login?error=registration-closed");
  }
  const { error } = await searchParams;

  return (
    <main className="auth-page">
      <section className="auth-shell">
        <div className="auth-intro">
          <span className="brand-mark" aria-hidden="true" />
          <div className="title-block">
            <h1>Create Account</h1>
            <p>Each user receives one persistent personal room that friends can enter without temporary links.</p>
          </div>
        </div>
      <section className="auth-card">
        <div className="title-block" style={{ marginBottom: 18 }}>
          <h1>Create account</h1>
          <p>Register a username and get a persistent room.</p>
        </div>
        {error ? <p className="form-error">{registerError(error)}</p> : null}
        <form className="form" action={registerUser}>
          <label>
            Username
            <input className="input" name="username" autoComplete="username" required />
          </label>
          <label>
            Password
            <input className="input" name="password" type="password" autoComplete="new-password" minLength={10} required />
          </label>
          {settings.registrationMode === "INVITE_ONLY" ? (
            <label>
              Invite code
              <input className="input" name="inviteCode" autoComplete="off" required />
            </label>
          ) : null}
          <button className="button primary" type="submit">
            Create account
          </button>
          <Link className="button" href="/login">
            Login instead
          </Link>
        </form>
      </section>
      </section>
    </main>
  );
}

function registerError(error: string) {
  if (error === "username") return "This username is already taken.";
  if (error === "closed") return "Registration is currently disabled by the administrator.";
  if (error === "invite") return "Use a valid active invite code.";
  return "Use a username and a password with at least 10 characters.";
}
