import { LoginForm } from "@/components/login-form";
import { signIn } from "@/lib/auth";
import { GalleryVerticalEndIcon } from "lucide-react";
import { AuthError } from "next-auth";
import { redirect } from "next/navigation";

async function authenticate(formData: FormData) {
    "use server";

    try {
        await signIn("credentials", {
            email: formData.get("email"),
            password: formData.get("password"),
            redirectTo: "/admin/dashboard",
        });
    } catch (error) {
        if (error instanceof AuthError) {
            redirect("/admin/login?error=CredentialsSignin");
        }

        throw error;
    }
}

export default async function LoginPage({
    searchParams,
}: {
    searchParams?: Promise<{ error?: string }>;
}) {
    const params = await searchParams;
    const error =
        params?.error === "CredentialsSignin"
            ? "账号或密码错误，请重试。"
            : undefined;

    return (
        <div className="bg-muted flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
            <div className="flex w-full max-w-sm flex-col gap-6">
                <div className="flex items-center gap-2 self-center font-medium">
                    <div className="bg-primary text-primary-foreground flex size-6 items-center justify-center rounded-md">
                        <GalleryVerticalEndIcon className="size-4" />
                    </div>
                    Wallora Admin
                </div>
                <LoginForm action={authenticate} error={error} />
            </div>
        </div>
    );
}
