import { Eye, EyeOff } from "lucide-react";
import { useRouter } from "next/router";
import { useState } from "react";
import toast from "react-hot-toast";
import { z } from "zod/v4";
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "~/components/custom_ui/form";
import Input from "~/components/custom_ui/input";
import { cn } from "~/lib/utils";
import { useZodForm } from "~/lib/zodForm";
import { useTranslation } from "~/providers/I18nProvider";
import { api } from "~/utils/api";

export const FormRstPwFromToken = (props: { token: string }) => {
	const { locale, t } = useTranslation();
	const router = useRouter();
	const [strengthScore, setStrengthScore] = useState(0);
	const [isVisible, setIsVisible] = useState<boolean>(false);
	const toggleVisibility = () => setIsVisible((prevState) => !prevState);

	const checkStrength = (pass: string) => {
		const requirements = [
			{ regex: /.{8,}/, text: t.auth.signup.pw.lenght },
			{ regex: /[0-9]/, text: t.auth.signup.pw.number },
			{ regex: /[a-z]/, text: t.auth.signup.pw.lowercase },
			{ regex: /[A-Z]/, text: t.auth.signup.pw.uppercase },
		];

		return requirements.map((req) => ({
			met: req.regex.test(pass),
			text: req.text,
		}));
	};

	const getStrengthColor = (score: number) => {
		if (score === 0) return "bg-border";
		if (score <= 1) return "bg-red-500";
		if (score <= 2) return "bg-orange-500";
		if (score === 3) return "bg-amber-500";
		return "bg-emerald-500";
	};
	const getStrengthTxt = (score: number) => {
		if (score === 0) return "text-border";
		if (score <= 1) return "text-red-500";
		if (score <= 2) return "text-orange-500";
		if (score === 3) return "text-amber-500";
		return "text-emerald-500";
	};

	const ResetFormSchema = z
		.object({
			password: z.string(),
			repeat_password: z.string(),
		})
		.superRefine(({ password, repeat_password }, refinementContext) => {
			const complexity = checkStrength(password);

			if (complexity.filter((req) => req.met).length !== complexity.length) {
				refinementContext.issues.push({
					code: "custom",
					input: "",
					message: complexity
						.filter((req) => !req.met)
						.map((req) => req.text)
						.join("\n"),
					path: ["password"],
				});
			}
			setStrengthScore(complexity.filter((req) => req.met).length);

			if (password !== repeat_password) {
				refinementContext.issues.push({
					code: "custom",
					input: "",
					message: t.pwReset.pwDiverse,
					path: ["repeat_password"],
				});
			}
		});

	const { mutate } = api.auth.resetPasswordFromToken.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success(t.pwReset.pwAggiornata);
			await router.push("/login");
		},
	});

	const form = useZodForm(ResetFormSchema, {
		defaultValues: {
			password: "",
			repeat_password: "",
		},
	});
	const onSubmit = (data: z.infer<typeof ResetFormSchema>) => {
		mutate({
			newpassword: data.password,
			resetToken: props.token,
		});
	};
	z.config(z.locales[locale]());

	return (
		<>
			<Form {...form}>
				<form
					className="space-y-8 px-0.5"
					onSubmit={form.handleSubmit(onSubmit)}
				>
					<FormField
						control={form.control}
						name="password"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-col gap-x-2">
									<FormLabel htmlFor="password">
										{t.auth.signup.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("password").invalid}
											className="pe-9"
											id="password"
											onChange={async (e) => {
												field.onChange(e);
												await form.trigger("password");
											}}
											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>
						)}
					/>

					<FormField
						control={form.control}
						name="repeat_password"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel
										className="font-medium text-base"
										htmlFor="password2"
									>
										{t.pwReset.ripetiPw}
									</FormLabel>

									<FormMessage />
								</div>
								<FormControl>
									<Input
										placeholder=""
										{...field}
										id="password2"
										type="password"
									/>
								</FormControl>
							</FormItem>
						)}
					/>
					<button
						className="w-full rounded-lg bg-red-600 px-4 py-2 font-medium text-white duration-150 hover:bg-red-500 active:bg-red-600"
						type="submit"
					>
						{t.pwReset.aggiorna}
					</button>
				</form>
			</Form>
		</>
	);
};
