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 { Button } from "~/components/ui/button";
import Input from "~/components/ui/input";
import { useZodForm } from "~/lib/zodForm";
import { useTranslation } from "~/providers/I18nProvider";
import { api } from "~/utils/api";

export const FormPswReset = () => {
	const router = useRouter();
	const LoginSchema = z.object({
		email: z.email(),
	});

	type LoginFormValues = z.infer<typeof LoginSchema>;

	const defaultValues: LoginFormValues = {
		email: "",
	};
	const { locale, t } = useTranslation();
	z.config(z.locales[locale]());

	const form = useZodForm(LoginSchema, {
		defaultValues: defaultValues,
	});

	const { mutate } = api.auth.sendResetLink.useMutation({
		onError: () => {
			toast.error(t.auth.login.fail);
		},
		onMutate: () => {
			setAlreadyRequested(true);
		},
		onSuccess: async () => {
			toast.success(
				"Verifica la tua casella di posta per il link di reset password",
			);
			await router.push("/login");
		},
	});
	const [altreadyRequested, setAlreadyRequested] = useState(false);
	function onSubmit(fields: LoginFormValues) {
		mutate({
			email: fields.email,
		});
		form.reset();
	}

	return (
		<>
			<div className="text-center">
				<div className="my-8 space-y-5">
					<h3 className="font-bold text-3xl text-gray-800 sm:text-3xl">
						{t.pwReset.titolo}
					</h3>
				</div>

				<Form {...form}>
					<form
						className="space-y-8 px-0.5"
						onSubmit={form.handleSubmit(onSubmit)}
					>
						<FormField
							control={form.control}
							name="email"
							render={({ field }) => (
								<FormItem>
									<div className="flex flex-wrap items-center gap-x-2">
										<FormLabel htmlFor="email">{t.pwReset.email}</FormLabel>{" "}
										<FormMessage />
									</div>

									<FormControl>
										<Input
											placeholder="esempio@email.com"
											{...field}
											id="email"
										/>
									</FormControl>
								</FormItem>
							)}
						/>

						<Button
							className="w-full rounded-lg bg-indigo-600 px-4 py-2 font-medium text-white duration-150 hover:bg-indigo-500 active:bg-indigo-600"
							disabled={altreadyRequested}
							type="submit"
						>
							{t.pwReset.get_link}
						</Button>
					</form>
				</Form>
			</div>
		</>
	);
};
