import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import {
  ADMIN_PASSWORD_ENV,
  ADMIN_SESSION_COOKIE,
  isAdminAuthEnabled,
  isValidAdminSession,
} from "@/lib/admin-auth";

function normalizeNext(value: string | string[] | undefined) {
  if (typeof value !== "string" || value.length === 0) return "/admin";
  if (!value.startsWith("/") || value.startsWith("//")) return "/admin";
  return value;
}

export default async function AdminLoginPage({
  searchParams,
}: {
  searchParams: Promise<{ next?: string; error?: string }>;
}) {
  const params = await searchParams;
  const next = normalizeNext(params.next);
  const cookieStore = await cookies();

  if (!isAdminAuthEnabled()) {
    redirect("/admin");
  }

  if (await isValidAdminSession(cookieStore.get(ADMIN_SESSION_COOKIE)?.value)) {
    redirect(next);
  }

  const hasError = params.error === "invalid_password";

  return (
    <main className="flex min-h-screen items-center justify-center admin-surface px-6">
      <section className="w-full max-w-md rounded-[2rem] border border-border/70 bg-card/95 p-8 shadow-[0_30px_100px_-40px_var(--glow-strong)]">
        <p className="text-xs uppercase tracking-[0.24em] text-primary">Admin access</p>
        <h1 className="mt-3 text-3xl font-semibold">Ingresar a Ballbox admin</h1>
        <p className="mt-3 text-sm leading-6 text-muted-foreground">
          Capa simple de acceso compartido. Configuracion actual: <span className="font-mono text-foreground">{ADMIN_PASSWORD_ENV}</span>
        </p>

        <form action="/api/admin/session" method="post" className="mt-6 space-y-4">
          <input type="hidden" name="next" value={next} />
          <div className="space-y-2">
            <label htmlFor="password" className="text-sm font-medium">
              Password
            </label>
            <input
              id="password"
              name="password"
              type="password"
              required
              autoFocus
              className="h-11 w-full rounded-xl border border-input bg-transparent px-4 text-sm outline-none transition focus:border-ring focus:ring-2 focus:ring-ring/50"
            />
          </div>

          {hasError ? (
            <p className="rounded-xl border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
              Password invalido.
            </p>
          ) : null}

          <button
            type="submit"
            className="inline-flex h-11 w-full items-center justify-center rounded-xl bg-primary px-4 text-sm font-medium text-primary-foreground transition hover:bg-primary/90"
          >
            Entrar
          </button>
        </form>
      </section>
    </main>
  );
}
