import { completePasswordResetAction } 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 { redirectToCanonicalMailAuthHostIfNeeded } from "@/lib/auth";
import { translate } from "@/lib/i18n-dictionaries";
import { resolveRequestLocale } from "@/lib/i18n-server";
import { toSearchString } from "@/lib/mail-urls";
import { getPasswordResetTokenStatus } from "@/lib/official-mail";

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

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

export default async function ResetPasswordTokenPage({
  params,
  searchParams,
}: ResetPasswordTokenPageProps) {
  const { token } = await params;
  const query = searchParams ? await searchParams : {};
  await redirectToCanonicalMailAuthHostIfNeeded(
    `/reset-password/${encodeURIComponent(token)}`,
    toSearchString(query),
  );

  const resetToken = token.trim();
  const tokenStatus = await getPasswordResetTokenStatus(resetToken);
  const error = pickParam(query.error);
  const locale = await resolveRequestLocale();
  const t = (key: Parameters<typeof translate>[1]) => translate(locale, key);
  const notice = error
    ? {
        tone: "error" as const,
        message:
          error === "required"
            ? t("auth.resetNew.required")
            : error === "password-mismatch"
              ? t("signup.error.passwordMismatch")
              : error === "invalid-token"
                ? t("auth.resetNew.invalidLink")
                : error === "used-token"
                  ? t("auth.resetNew.usedLink")
                  : error === "expired-token"
                    ? t("auth.resetNew.expiredLink")
                    : t("auth.resetNew.failed"),
      }
    : null;

  return (
    <AuthPageShell
      title="auth.resetNew.title"
      description="auth.resetNew.description"
    >
      <DismissibleBottomToast
        notice={notice}
        clearSearchParams={["error", "success", "details"]}
      />

      {tokenStatus.status === "valid" ? (
        <form action={completePasswordResetAction} className="space-y-4">
          <input type="hidden" name="token" value={resetToken} />

          <label className="block">
            <span className="mb-2 block text-[13px] font-medium text-[#6f7784]">
              {t("auth.resetNew.password")}
            </span>
            <input
              required
              type="password"
              name="password"
              autoComplete="new-password"
              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.resetNew.placeholder")}
            />
          </label>

          <label className="block">
            <span className="mb-2 block text-[13px] font-medium text-[#6f7784]">
              {t("auth.resetNew.confirm")}
            </span>
            <input
              required
              type="password"
              name="passwordConfirm"
              autoComplete="new-password"
              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.resetNew.confirmPlaceholder")}
            />
          </label>

          <SubmitButton
            label={t("auth.resetNew.submit")}
            pendingLabel={t("auth.resetNew.updating")}
            className="om-btn-primary h-12 w-full rounded-[12px] px-5 text-[14px] font-semibold"
          />
        </form>
      ) : (
        <div>
          <p role="alert" className="text-[13px] font-medium leading-6 text-[#bd4052]">
            {tokenStatus.status === "used"
              ? t("auth.resetNew.usedLink")
              : tokenStatus.status === "expired"
                ? t("auth.resetNew.expiredLinkLong")
                : t("auth.resetNew.invalidLink")}
          </p>
          <div className="mt-3 text-[13px] text-[#5d6777]">
            <AuthTransitionLink
              href="/reset-password"
              className="font-semibold text-[#2f6df6]"
            >
              {t("auth.resetNew.back")}
            </AuthTransitionLink>
          </div>
        </div>
      )}
    </AuthPageShell>
  );
}
