"use client";

import { Eye, EyeOff, Frown } from "lucide-react";
import type { GetServerSideProps } from "next";
import { useRouter } from "next/router";
import toast from "react-hot-toast";
import { z } from "zod";
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "~/components/custom_ui/form";
import { PasswordSVG } from "~/components/svgs";
import { Button } from "~/components/ui/button";
import Input from "~/components/ui/input";
import { useStrongPassword } from "~/hooks/useStrongPassword";
import { cn } from "~/lib/utils";
import { useZodForm } from "~/lib/zodForm";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";

type Valid = {
	valid: true;
	token: string;
	email: string;
};
type Invalid = {
	valid: false;
	token: null;
	email: null;
};
type InviteTokenProps = Valid | Invalid;
/**
 * Pagina di accettazione invito: /auth/accetta-invito/[token]
 */
const AcceptInvitePage: NextPageWithLayout<InviteTokenProps> = ({
	valid,
	token,
	email,
}: InviteTokenProps) => {
	const {
		isVisible,
		getStrengthColor,
		passwordRefine,
		getStrengthTxt,
		strengthScore,
		toggleVisibility,
	} = useStrongPassword();
	const router = useRouter();

	const schema = z
		.object({
			newPsw: z.string(),
		})
		.superRefine(({ newPsw }, refinementContext) => {
			passwordRefine({
				password: newPsw,
				path: "newPsw",
				refinementContext,
			});
		});

	type FormValues = z.infer<typeof schema>;

	const { locale } = useTranslation();

	z.config(z.locales[locale]());

	const form = useZodForm(schema, {
		defaultValues: {
			newPsw: "",
		},
	});

	function onSubmit(fields: FormValues) {
		if (!email || !token) return;
		acceptInvite({
			email,
			password: fields.newPsw,
			token,
		});
	}

	const { mutate: acceptInvite, isPending } =
		api.invite.acceptInvite.useMutation({
			onSuccess: async () => {
				toast.success("Account creato! Effettua il login.");
				await router.push("/login?redirect=/area-riservata/dashboard");
			},
			onError: (error) => {
				toast.error(error.message);
			},
		});

	if (!valid) {
		return (
			<div className="flex flex-1 flex-col items-center justify-center gap-2 text-center">
				<Frown className="mx-auto mb-4 size-28 text-muted-foreground" />

				<h1 className="font-bold text-xl">Questo link non valido</h1>
				<p>Il link è scaduto o è già stato utilizzato.</p>
				<p>Contattaci per ricevere una nuova email.</p>
			</div>
		);
	}

	return (
		<div className="mx-auto w-full max-w-lg space-y-10 py-6 md:py-10">
			<div className="flex w-full items-center justify-center">
				<PasswordSVG className="size-48" />
			</div>

			<Form {...form}>
				<form className="space-y-6 px-4" onSubmit={form.handleSubmit(onSubmit)}>
					<h1 className="font-bold text-2xl">Scegli la tua password</h1>
					<FormField
						control={form.control}
						name="newPsw"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-col gap-x-2">
									<FormLabel htmlFor="newPsw">Scegli una password</FormLabel>

									<FormMessage
										className={cn(
											"whitespace-pre-wrap",
											getStrengthTxt(strengthScore),
										)}
									/>
								</div>

								<FormControl>
									<div className="relative">
										<Input
											{...field}
											aria-describedby="password-strength"
											aria-invalid={form.getFieldState("newPsw").invalid}
											autoComplete="new-password"
											className="pe-9"
											id="newPsw"
											onChange={async (e) => {
												field.onChange(e);
												await form.trigger("newPsw");
											}}
											placeholder="Password"
											type={isVisible ? "text" : "password"}
										/>
										<button
											aria-controls="password"
											aria-label={isVisible ? "Hide password" : "Show password"}
											aria-pressed={isVisible}
											className="absolute end-0 top-1 flex size-9 items-center justify-center rounded-e-lg text-muted-foreground/80 transition-shadow hover:text-foreground focus-visible:border focus-visible:border-ring focus-visible:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring/30 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
											onClick={toggleVisibility}
											type="button"
										>
											{isVisible ? (
												<EyeOff aria-hidden="true" size={16} strokeWidth={2} />
											) : (
												<Eye aria-hidden="true" size={16} strokeWidth={2} />
											)}
										</button>
										<div
											aria-label="Password strength"
											aria-valuemax={4}
											aria-valuemin={0}
											aria-valuenow={strengthScore}
											className="mt-3 mb-4 h-1 w-full overflow-hidden rounded-full bg-border"
											role="progressbar"
										>
											<div
												className={cn(
													"h-full transition-all duration-500 ease-out",
													getStrengthColor(strengthScore),
												)}
												style={{ width: `${(strengthScore / 4) * 100}%` }}
											/>
										</div>
									</div>
								</FormControl>
							</FormItem>
						)}
					/>

					<Button disabled={!form.formState.isValid || isPending} type="submit">
						Procedi
					</Button>
				</form>
			</Form>
		</div>
	);
};

export default AcceptInvitePage;

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.invite.verifyInvite.fetch({ token });

	if (valid.valid) {
		return {
			props: {
				valid: true,
				token,
				email: valid.email as string,
			},
		};
	}
	return {
		props: {
			valid: false,
			token: null,
			email: null,
		},
	};
}) satisfies GetServerSideProps<InviteTokenProps>;
