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

type ResetWTokenProps = {
	token: string;
};
/**
 * Pagina di reset password con token: /auth/password-reset/[token]
 */
const ResetWToken: NextPageWithLayout<ResetWTokenProps> = ({
	token,
}: ResetWTokenProps) => {
	const { t } = useTranslation();

	return (
		<>
			<Head>
				<title>{t.heads.main_titolo}</title>
				<meta content={t.heads.main_description} name="description" />
			</Head>
			<main className="py-14">
				<div className="mx-auto max-w-7xl 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="font-semibold text-3xl text-accent-foreground 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,
			},
		};
	}
	return {
		redirect: {
			destination: "/auth/nonvalid-password-reset-token",
			permanent: false,
		},
	};
}) satisfies GetServerSideProps<ResetWTokenProps>;
