import { Eye, EyeOff } from "lucide-react";
import { useRouter } from "next/router";
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/ui/input";
import { usePassword } from "~/hooks/usePassword";
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 {
		isVisible,
		getStrengthColor,
		passwordRefine,
		getStrengthTxt,
		strengthScore,
		toggleVisibility,
		maxStrength,
	} = usePassword();

	const ResetFormSchema = z
		.object({
			password: z.string(),
			repeat_password: z.string(),
		})
		.superRefine(({ password, repeat_password }, refinementContext) => {
			passwordRefine({
				password,
				path: "password",
				refinementContext,
			});
			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 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>
						)}
					/>

					<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>
		</>
	);
};
