import { redirect } from "next/navigation";
import { setAdminCookie, verifyPassword, isAdmin } from "@/lib/admin-auth";

export const metadata = { title: "Admin login — PIFF" };

async function loginAction(formData: FormData) {
  "use server";
  const password = String(formData.get("password") ?? "");
  if (!verifyPassword(password)) {
    redirect("/admin/login?error=1");
  }
  setAdminCookie();
  redirect("/admin/moderate");
}

interface PageProps {
  searchParams: { error?: string };
}

export default function AdminLoginPage({ searchParams }: PageProps) {
  if (isAdmin()) redirect("/admin/moderate");
  return (
    <section className="mx-auto max-w-sm px-6 py-20">
      <h1 className="font-display text-2xl font-bold text-text">
        Admin sign-in
      </h1>
      <form action={loginAction} className="mt-6 space-y-3">
        <input
          type="password"
          name="password"
          required
          autoComplete="current-password"
          placeholder="Admin password"
          className="w-full rounded-lg border border-border bg-white p-3 text-text"
        />
        {searchParams.error && (
          <div className="rounded-md bg-red-50 p-2 text-sm text-red-700">
            Incorrect password.
          </div>
        )}
        <button
          type="submit"
          className="w-full rounded-full bg-primary py-2.5 font-medium text-white hover:bg-primaryDark"
        >
          Sign in
        </button>
      </form>
    </section>
  );
}
