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 { Button } from "~/components/ui/button";
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 ChangePasswordForm = () => {
	const {
		isVisible,
		getStrengthColor,
		passwordRefine,
		getStrengthTxt,
		strengthScore,
		maxStrength,
		toggleVisibility,
	} = usePassword();
	const router = useRouter();

	const ChangePasswordFormSchema = z
		.object({
			oldPsw: z.string().min(1, "Inserisci la password corrente"),
			newPsw: z.string(),
			confirmPsw: z.string().min(1, "Ripeti la nuova password"),
		})
		.superRefine(({ oldPsw, newPsw, confirmPsw }, refinementContext) => {
			passwordRefine({
				password: newPsw,
				path: "newPsw",
				refinementContext,
			});
			if (oldPsw === newPsw) {
				refinementContext.addIssue({
					code: "custom",
					message: "La nuova password deve essere diversa da quella corrente",
					path: ["newPsw"],
				});
			}
			if (newPsw !== confirmPsw) {
				refinementContext.addIssue({
					code: "custom",
					message: "Le password non coincidono",
					path: ["confirmPsw"],
				});
			}
		});

	type ChangePasswordFormValues = z.infer<typeof ChangePasswordFormSchema>;

	const { locale, t } = useTranslation();

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

	const form = useZodForm(ChangePasswordFormSchema, {
		defaultValues: {
			newPsw: "",
			oldPsw: "",
			confirmPsw: "",
		},
	});

	const { mutate } = api.auth.ChangePassword.useMutation({
		onError: (error) => {
			toast.error(error.message);
		},
		onSuccess: async () => {
			toast.success(t.pwReset.pwAggiornata);
			form.reset();
			await router.push("/area-riservata/dashboard");
		},
	});

	function onSubmit(fields: ChangePasswordFormValues) {
		mutate({
			newpassword: fields.newPsw,
			oldpassword: fields.oldPsw,
		});
	}

	return (
		<Form {...form}>
			<form className="space-y-8 px-0.5" onSubmit={form.handleSubmit(onSubmit)}>
				<FormField
					control={form.control}
					name="oldPsw"
					render={({ field }) => (
						<FormItem>
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="oldpw">{t.pwReset.oldPw}</FormLabel>
								<FormMessage />
							</div>
							<FormControl>
								<Input
									placeholder=""
									{...field}
									autoComplete="current-password"
									id="oldpw"
								/>
							</FormControl>
						</FormItem>
					)}
				/>

				<FormField
					control={form.control}
					name="newPsw"
					render={({ field }) => (
						<FormItem>
							<div className="flex flex-col gap-x-2">
								<FormLabel htmlFor="newPsw">{t.pwReset.newPw}</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>
					)}
				/>
				<FormField
					control={form.control}
					name="confirmPsw"
					render={({ field }) => (
						<FormItem>
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="confirmpw">{t.pwReset.confirmPw}</FormLabel>
								<FormMessage />
							</div>
							<FormControl>
								<Input
									placeholder=""
									{...field}
									autoComplete="off"
									id="confirmpw"
									type="password"
								/>
							</FormControl>
						</FormItem>
					)}
				/>
				<Button type="submit">{t.pwReset.aggiorna}</Button>
			</form>
		</Form>
	);
};
