import type { GetServerSideProps } from "next";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
import Head from "next/head";
import { FormRstPwFromToken } from "~/forms/FormRstPwFromToken";
import { generateSSGHelper } from "~/server/utils/ssgHelper";

type ResetWTokenProps = {
  token: string;
};

const ResetWToken: NextPageWithLayout<ResetWTokenProps> = ({
  token,
}: ResetWTokenProps) => {
  const { t } = useTranslation();

  return (
    <>
      <Head>
        <title>{t.heads.main_titolo}</title>
        <meta name="description" content={t.heads.main_description} />
      </Head>
      <main className="py-14">
        <div className="mx-auto max-w-screen-xl px-4 text-neutral-600 md:px-8 dark:text-white">
          <div className="mx-auto max-w-lg space-y-3 sm:text-center">
            <p className="text-accent-foreground text-3xl font-semibold sm:text-4xl dark:text-white">
              {t.pwReset.titolo}
            </p>
          </div>
          <div className="mx-auto mt-12 max-w-lg">
            <FormRstPwFromToken token={token} />
          </div>
        </div>
      </main>
    </>
  );
};

export default ResetWToken;

export const getServerSideProps = (async (context) => {
  const token = context.params?.token;

  if (typeof token !== "string") {
    return {
      redirect: {
        destination: "/auth/nonvalid-password-reset-token",
        permanent: false,
      },
    };
  }

  const helper = generateSSGHelper();

  const valid = await helper.auth.checkTokenValidity.fetch({ token });
  if (valid) {
    return {
      props: {
        token,
      },
    };
  } else {
    return {
      redirect: {
        destination: "/auth/nonvalid-password-reset-token",
        permanent: false,
      },
    };
  }
}) satisfies GetServerSideProps<ResetWTokenProps>;
