import { redirect } from "next/navigation";
import { requestPasswordResetAction } from "@/app/actions/session";
import { AuthPageShell } from "@/components/auth-page-shell";
import { AuthTransitionLink } from "@/components/auth-transition";
import { DismissibleBottomToast } from "@/components/dismissible-bottom-toast";
import { SubmitButton } from "@/components/submit-button";
import {
  getMailEntryUrlForCurrentRequest,
  getSessionUser,
  redirectToCanonicalMailAuthHostIfNeeded,
} from "@/lib/auth";
import { translate } from "@/lib/i18n-dictionaries";
import { resolveRequestLocale } from "@/lib/i18n-server";
import { toSearchString } from "@/lib/mail-urls";

type ResetPasswordPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

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

export default async function ResetPasswordPage({
  searchParams,
}: ResetPasswordPageProps) {
  const params = searchParams ? await searchParams : {};
  await redirectToCanonicalMailAuthHostIfNeeded(
    "/reset-password",
    toSearchString(params),
  );
  const user = await getSessionUser();
  const error = pickParam(params.error);
  const success = pickParam(params.success);
  const masked = pickParam(params.masked);
  const locale = await resolveRequestLocale();
  const t = (key: Parameters<typeof translate>[1], values?: Record<string, string | number>) =>
    translate(locale, key, values);
  const notice = error
    ? {
        tone: "error" as const,
        message:
          error === "required"
            ? t("auth.reset.required")
            : error === "not-found"
              ? t("auth.reset.notFound")
              : error === "recovery-email-missing"
                ? t("auth.reset.recoveryMissing")
                : t("auth.reset.sendFailed"),
      }
    : success === "link-sent"
      ? {
          tone: "success" as const,
          message: masked
            ? t("auth.reset.sentMasked", { email: masked })
            : t("auth.reset.sent"),
        }
      : null;

  if (user) {
    redirect(await getMailEntryUrlForCurrentRequest(user));
  }

  return (
    <AuthPageShell
      title="auth.reset.title"
      description="auth.reset.description"
    >
      <DismissibleBottomToast
        notice={notice}
        clearSearchParams={["error", "success", "details", "masked"]}
      />
      <form action={requestPasswordResetAction} className="space-y-4">
        <label className="block">
          <span className="mb-2 block text-[13px] font-medium text-[#6f7784]">
            {t("auth.reset.loginEmail")}
          </span>
          <input
            required
            type="email"
            name="email"
            className="h-12 w-full rounded-[12px] border border-[#d7deea] px-4 text-[14px] text-[#101418] outline-none transition-colors focus:border-[#2f6df6]"
            placeholder={t("auth.email.placeholder")}
          />
        </label>

        <label className="block">
          <span className="mb-2 block text-[13px] font-medium text-[#6f7784]">
            {t("signup.businessName")}
          </span>
          <input
            required
            type="text"
            name="companyName"
            className="h-12 w-full rounded-[12px] border border-[#d7deea] px-4 text-[14px] text-[#101418] outline-none transition-colors focus:border-[#2f6df6]"
            placeholder={t("signup.businessName.placeholder")}
          />
        </label>

        <SubmitButton
          label={t("auth.reset.submit")}
          pendingLabel={t("auth.reset.sending")}
          className="om-btn-primary h-12 w-full rounded-[12px] px-5 text-[14px] font-semibold"
        />
      </form>

      <div className="mt-6 text-center text-[14px] text-[#7f8791]">
        {t("auth.reset.backPrompt")}{" "}
        <AuthTransitionLink href="/login" className="font-semibold text-[#2f6df6]">
          {t("auth.login")}
        </AuthTransitionLink>
      </div>
    </AuthPageShell>
  );
}
