import Link from "next/link";
import { loginUser } 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 LoginPage({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
  if (!(await hasAdminUser())) {
    redirect("/setup");
  }
  const settings = await getAppSettings();
  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>WatchLink</h1>
            <p>Persistent watch rooms with local accounts, friends, and synchronized playback.</p>
          </div>
        </div>
        <div className="auth-card">
        <div className="title-block" style={{ marginBottom: 18 }}>
          <h1>Login</h1>
          <p>Enter your account to open rooms and manage playback.</p>
        </div>
        {error ? <p className="form-error">{loginError(error)}</p> : null}
        <form className="form" action={loginUser}>
          <label>
            Username
            <input className="input" name="username" autoComplete="username" required />
          </label>
          <label>
            Password
            <input className="input" name="password" type="password" autoComplete="current-password" required />
          </label>
          <button className="button primary" type="submit">
            Login
          </button>
          {settings.registrationMode === "OPEN" ? (
            <Link className="button" href="/register">
              Create account
            </Link>
          ) : (
            <p className="disabled-note">Registration is {settings.registrationMode.toLowerCase().replace("_", " ")}.</p>
          )}
        </form>
        </div>
      </section>
    </main>
  );
}

function loginError(error: string) {
  if (error === "registration-closed") return "Registration is currently disabled by the administrator.";
  if (error === "disabled") return "This account has been disabled by an administrator.";
  return "Invalid username or password.";
}
