import type { Metadata } from "next";
import Link from "next/link";
import { AuthShell } from "../_components/auth-shell";
import { SignInForm } from "./signin-form";
import { authTexts } from "@/lib/i18n/auth";
import { commonTexts } from "@/lib/i18n/common";

export const metadata: Metadata = {
  title: `${authTexts.signInTitle} · ${commonTexts.appName}`,
  description: authTexts.signInSubtitle,
};

type SearchParams = Record<string, string | string[] | undefined>;

function first(value: string | string[] | undefined): string {
  if (Array.isArray(value)) return value[0] ?? "";
  return value ?? "";
}

export default async function SignInPage(props: {
  searchParams: Promise<SearchParams>;
}) {
  const searchParams = await props.searchParams;
  const callbackRaw = first(searchParams.callbackUrl);
  const callbackUrl =
    callbackRaw.startsWith("/") && !callbackRaw.startsWith("//") ? callbackRaw : "/";

  const error = first(searchParams.error);
  const registered = first(searchParams.registered);
  const reset = first(searchParams.reset);

  let notice: { tone: "error" | "info" | "success"; message: string } | null = null;
  if (error === "suspended") {
    notice = { tone: "error", message: authTexts.errors.suspended };
  } else if (error) {
    notice = { tone: "error", message: authTexts.errors.invalidCredentials };
  } else if (registered) {
    notice = { tone: "success", message: authTexts.accountCreated };
  } else if (reset) {
    notice = { tone: "success", message: authTexts.resetDone };
  }

  return (
    <AuthShell
      title={authTexts.signInTitle}
      description={authTexts.signInSubtitle}
      footer={
        <>
          {authTexts.noAccount}{" "}
          <Link
            href="/signup"
            className="font-medium text-primary transition-colors hover:text-primary/80"
          >
            {authTexts.createAccount}
          </Link>
        </>
      }
    >
      <SignInForm callbackUrl={callbackUrl} notice={notice} />
    </AuthShell>
  );
}
