import Link from "next/link";
import { redirect } from "next/navigation";

import { auth } from "@/auth";
import { getPostLoginRedirect } from "@/lib/post-login-redirect";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";

import { LoginForm } from "./login-form";

export const metadata = { title: "Anmelden · Kita-Planer" };

type LoginPageProps = {
  searchParams?: Promise<{ callbackUrl?: string | string[] }>;
};

function getSafeCallbackUrl(value: string | string[] | undefined) {
  const callbackUrl = Array.isArray(value) ? value[0] : value;
  if (!callbackUrl) return "/dashboard";
  if (!callbackUrl.startsWith("/") || callbackUrl.startsWith("//")) {
    return "/dashboard";
  }
  return callbackUrl;
}

export default async function LoginPage({ searchParams }: LoginPageProps) {
  const session = await auth();
  if (session?.user?.id) {
    redirect(getPostLoginRedirect(session.user));
  }
  const resolvedSearchParams = await searchParams;
  const callbackUrl = getSafeCallbackUrl(resolvedSearchParams?.callbackUrl);

  return (
    <div className="flex min-h-screen items-center justify-center bg-muted/30 px-4 py-12">
      <Card className="w-full max-w-md">
        <CardHeader className="space-y-2">
          <CardTitle>Anmelden</CardTitle>
          <CardDescription>Willkommen zurück.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <LoginForm callbackUrl={callbackUrl} />
          <p className="text-center text-sm text-muted-foreground">
            Noch keinen Account?{" "}
            <Link href="/register" className="font-medium text-foreground underline">
              Kita registrieren
            </Link>
          </p>
        </CardContent>
      </Card>
    </div>
  );
}
