import { notFound, redirect } from "next/navigation";
import { isLocale, type Locale } from "@/lib/i18n/config";
import { getDictionary } from "@/lib/i18n";
import { getSessionUser } from "@/lib/auth-helpers";
import { safeCallbackPath } from "@/lib/utils";
import { buildMetadata } from "@/lib/seo";
import { AuthShell } from "@/components/store/auth-shell";
import { RegisterForm } from "@/components/store/register-form";

export async function generateMetadata({ params }: { params: Promise<{ locale: string }> }) {
  const { locale: raw } = await params;
  if (!isLocale(raw)) return {};
  const locale = raw as Locale;
  const dict = getDictionary(locale);
  return buildMetadata({
    locale,
    title: `${dict.auth.registerTitle} — DAR ZELLIGE`,
    description: dict.auth.registerDescription,
    path: "/register",
    noIndex: true,
  });
}

export default async function RegisterPage({
  params,
  searchParams,
}: {
  params: Promise<{ locale: string }>;
  searchParams: Promise<{ callbackUrl?: string }>;
}) {
  const { locale: raw } = await params;
  if (!isLocale(raw)) notFound();
  const locale = raw as Locale;
  const dict = getDictionary(locale);
  const user = await getSessionUser();
  if (user) redirect(`/${locale}/account`);

  const query = await searchParams;
  const callbackUrl = safeCallbackPath(query.callbackUrl || `/${locale}/account`, locale);

  return (
    <AuthShell
      locale={locale}
      image="/images/story-pottery.jpg"
      imageAlt={dict.story.imageCaption}
      quote={dict.story.p2.split(".")[0]}
      caption={dict.story.imageCaption}
      backLabel={dict.errors.backHome}
    >
      <RegisterForm
        locale={locale}
        loginHref={`/${locale}/login?callbackUrl=${encodeURIComponent(callbackUrl)}`}
        labels={{
          title: dict.auth.registerTitle,
          description: dict.auth.registerDescription,
          name: dict.auth.name,
          email: dict.auth.email,
          phone: dict.auth.phone,
          password: dict.auth.password,
          confirmPassword: dict.auth.confirmPassword,
          register: dict.auth.register,
          creating: dict.auth.creating,
          hint: dict.auth.passwordHint,
          mismatch: dict.auth.passwordMismatch,
          hasAccount: dict.auth.hasAccount,
          login: dict.auth.login,
          terms: dict.checkout.terms,
          termsLink: dict.footer.terms,
          privacyLink: dict.footer.privacy,
        }}
      />
    </AuthShell>
  );
}
