import { login, logout } from "@/actions/auth";
import { Button } from "@/components/ui/Button";
import { CONTROL_CLASS } from "@/components/ui/Field";

// The query string is attacker-controlled, so the login page renders a message
// looked up by code rather than whatever text ?error= carries. Reflecting the
// raw parameter let anyone put arbitrary wording ("Ihr Konto wurde gesperrt,
// rufen Sie …") on the real, correctly-branded sign-in screen.
const ERROR_MESSAGES = {
  no_hr_access: "Kein HR-Zugriff. Bitte wenden Sie sich an eine:n bestehende:n HR-Benutzer:in.",
  invalid_credentials: "E-Mail oder Passwort ist falsch.",
} as const;

type ErrorCode = keyof typeof ERROR_MESSAGES;

type LoginPageProps = {
  searchParams: Promise<{ error?: string }>;
};

export default async function LoginPage({ searchParams }: LoginPageProps) {
  const params = await searchParams;
  const code = params.error && Object.hasOwn(ERROR_MESSAGES, params.error) ? (params.error as ErrorCode) : null;
  const error = code ? ERROR_MESSAGES[code] : null;

  return (
    <div className="flex min-h-screen items-center justify-center bg-surface px-4">
      <div className="w-full max-w-sm rounded border border-border bg-white p-8 shadow-sm">
        <h1 className="text-xl font-extrabold text-ink">Alpenwerk HR</h1>
        <p className="mt-1 text-sm text-ink-muted">Melden Sie sich mit Ihrem Firmenkonto an.</p>

        {error && (
          <div role="alert" className="mt-4 rounded bg-danger-bg px-3 py-2 text-sm text-danger-text">
            {error}
            {code === "no_hr_access" && (
              <form action={logout} className="mt-2">
                <button type="submit" className="text-xs font-semibold underline hover:no-underline">
                  Abmelden und mit anderem Konto versuchen
                </button>
              </form>
            )}
          </div>
        )}

        <form action={login} className="mt-6 flex flex-col gap-4">
          <div>
            <label htmlFor="email" className="mb-1 block text-sm font-semibold text-ink">
              E-Mail
            </label>
            <input
              id="email"
              name="email"
              type="email"
              required
              autoComplete="username"
              className={CONTROL_CLASS}
            />
          </div>
          <div>
            <label htmlFor="password" className="mb-1 block text-sm font-semibold text-ink">
              Passwort
            </label>
            <input
              id="password"
              name="password"
              type="password"
              required
              autoComplete="current-password"
              className={CONTROL_CLASS}
            />
          </div>
          <Button type="submit" fullWidth className="mt-2">
            Anmelden
          </Button>
        </form>
      </div>
    </div>
  );
}
