"use client";

import {
	ExternalLink,
	Eye,
	EyeOff,
	Frown,
	MailPlus,
	UserSearch,
} 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 { Status500 } from "~/components/status-page";
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 { usePassword } from "~/hooks/usePassword";
import { cn, redirectTo500 } from "~/lib/utils";
import { useZodForm } from "~/lib/zodForm";
import type { NextPageWithLayout } from "~/pages/_app";
import { useTranslation } from "~/providers/I18nProvider";
import type {
	InviteErrors,
	TokenVerErrors,
} from "~/server/controllers/invites.controller";
import { generateSSGHelper } from "~/server/utils/ssgHelper";
import { api } from "~/utils/api";
import type { Result } from "~/utils/result";
import { assertNever } from "~/utils/utils";

type InviteTokenProps = {
	token: string;
	verification: Result<string, InviteErrors>;
};

/**
 * Pagina di accettazione invito: /auth/accetta-invito/[token]
 */
const AcceptInvitePage: NextPageWithLayout<InviteTokenProps> = ({
	verification,
	token,
}: InviteTokenProps) => {
	if (!verification.ok) {
		switch (verification.error._tag) {
			case "AlreadyUser":
				return <AlreadyUserPage />;
			case "Expired":
			case "TokenNotFound":
				return <InvalidInvitePage reason={verification.error._tag} />;
			case "InternalError":
				return <Status500 />;
			default:
				assertNever(verification.error);
		}
	}
	return <ValidInvitePage email={verification.value} token={token} />;
};
const ValidInvitePage = ({
	token,
	email,
}: {
	token: string;
	email: string;
}) => {
	const {
		isVisible,
		getStrengthColor,
		passwordRefine,
		getStrengthTxt,
		strengthScore,
		toggleVisibility,
		maxStrength,
	} = usePassword();
	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 (result) => {
				if (!result.ok) {
					switch (result.error._tag) {
						case "UserNotFound":
							toast.error(result.error.message);
							return;
						case "TokenNotFound":
						case "Expired":
							toast.error(
								"Il token di invito non è più valido. Richiedi un nuovo invito.",
							);
							window.location.reload();
							return;

						default:
							assertNever(result.error);
					}
				}
				toast.success(
					"Successo! La tua password è stata impostata. Reindirizzamento in corso...",
				);
				await router.push("/area-riservata/dashboard");
			},
			onError: (error) => {
				toast.error(error.message);
			},
		});
	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 AlreadyUserPage = () => {
	return (
		<div className="flex flex-1 flex-col items-center justify-center gap-2 text-center">
			<UserSearch className="mx-auto mb-4 size-28 text-muted-foreground" />
			<h1 className="font-bold text-xl">Utente già registrato</h1>
			<p>L'email associata a questo invito è già registrata.</p>
			<div className="flex flex-col items-center gap-4 pt-4 md:flex-row">
				<Link href="/login">
					<Button size="lg" variant="info">
						<span>Vai al Login</span>
						<ExternalLink />
					</Button>
				</Link>
			</div>
		</div>
	);
};

const InvalidInvitePage = ({ reason }: { reason: TokenVerErrors["_tag"] }) => {
	const message =
		reason === "Expired"
			? "L'invito è scaduto, è passato troppo tempo dall'invio."
			: "Non è stato trovato alcun invito valido per questo collegamento.";

	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>{message}</p>
			<div className="flex flex-col items-center gap-4 pt-4 md:flex-row">
				<NewInviteDialog />
			</div>
		</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 size="lg">
					<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 e = context.query.e;
	let email: string | null = null;
	if (typeof e === "string") {
		try {
			email = atob(e);
		} catch {
			email = null;
		}
	}

	const helper = generateSSGHelper();

	const verification = await helper.invite.verifyInvite.fetch({ token, email });

	if (!verification.ok && verification.error._tag === "InternalError") {
		return redirectTo500;
	}

	return {
		props: {
			verification,
			token,
		},
	};
}) satisfies GetServerSideProps<InviteTokenProps>;
