"use client";

import { ExternalLink, Eye, EyeOff, Frown, MailPlus } from "lucide-react";
import type { GetServerSideProps } from "next";
import Link from "next/link";
import { useRouter } from "next/router";
import { useState } from "react";
import toast from "react-hot-toast";
import { z } from "zod";
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "~/components/custom_ui/form";
import LoadingButton from "~/components/custom_ui/loading-button";
import { PasswordSVG } from "~/components/svgs";
import {
	AlertDialog,
	AlertDialogAction,
	AlertDialogCancel,
	AlertDialogContent,
	AlertDialogDescription,
	AlertDialogFooter,
	AlertDialogHeader,
	AlertDialogTitle,
	AlertDialogTrigger,
} from "~/components/ui/alert-dialog";
import { Button } from "~/components/ui/button";
import Input from "~/components/ui/input";
import { useMildPassword } from "~/hooks/usePassword";
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,
		maxStrength,
	} = useMildPassword();
	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("/area-riservata/dashboard");
				//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">Invito non valido</h1>
				<p>L'invito è scaduto o è già stato utilizzato.</p>
				<div className="flex flex-col items-center gap-4 pt-4 md:flex-row">
					<Link href="/login">
						<Button variant="info">
							<span>Vai al Login</span>
							<ExternalLink />
						</Button>
					</Link>
					<NewInviteDialog />
				</div>
			</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 cursor-pointer 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={maxStrength}
											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 / maxStrength) * 100}%`,
												}}
											/>
										</div>
									</div>
								</FormControl>
							</FormItem>
						)}
					/>
					<h1>La utilizzerai per accedere al tuo account</h1>

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

const NewInviteDialog = () => {
	const { t } = useTranslation();
	const [email, setEmail] = useState("");
	const [open, setOpen] = useState(false);
	const { mutate, isPending } = api.invite.requestNewInvite.useMutation({
		onSuccess: () => {
			toast.success("Email inviata! Controlla la tua casella di posta.", {
				duration: 5000,
			});
			setOpen(false);
			setEmail("");
		},
		onError: (error) => {
			toast.error(error.message);
			setOpen(false);
			setEmail("");
		},
	});

	return (
		<AlertDialog onOpenChange={setOpen} open={open}>
			<AlertDialogTrigger asChild>
				<Button>
					<span>Richiedi un nuovo invito</span>
					<MailPlus />
				</Button>
			</AlertDialogTrigger>
			<AlertDialogContent>
				<AlertDialogHeader>
					<AlertDialogTitle>Inserisci il tuo indirizzo email</AlertDialogTitle>
					<AlertDialogDescription>
						Inserisci l'indirizzo email associato al tuo account per ricevere un
						nuovo invito.
					</AlertDialogDescription>
				</AlertDialogHeader>

				<Input
					autoComplete="off"
					id="email"
					onChange={(e) => setEmail(e.target.value)}
					placeholder="esempio@email.com"
					type="email"
					value={email}
				/>

				<AlertDialogFooter>
					<AlertDialogCancel>{t.cancella}</AlertDialogCancel>
					<AlertDialogAction asChild>
						<LoadingButton
							disabled={!email || email.trim() === "" || !email.includes("@")}
							loading={isPending}
							onClick={() => mutate({ email })}
							variant="default"
						>
							{t.procedi}
						</LoadingButton>
					</AlertDialogAction>
				</AlertDialogFooter>
			</AlertDialogContent>
		</AlertDialog>
	);
};
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>;
