import { CheckCircle } from "lucide-react";
import { useState } from "react";
import toast from "react-hot-toast";
import { useLocalStorage } from "react-use";
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 { Textarea } from "~/components/custom_ui/textarea";
import { PhoneInput } from "~/components/phone-input";
import { Checkbox } from "~/components/ui/checkbox";
import { useZodForm } from "~/lib/zodForm";
import { useTranslation } from "~/providers/I18nProvider";
import { api } from "~/utils/api";

type UserContattoData = {
	nome: string;
	email: string;
	telefono: string;
};

export const FormContattoAnnucio = ({ codice }: { codice: string }) => {
	const { locale, t } = useTranslation();
	const [hasSent, setHasSent] = useState(false);
	const schema = z.object({
		checkbox: z.boolean().refine((val) => val === false), // Honeypot field

		email: z.email(),
		messaggio: z.string().nonempty("Inserisci un messaggio"),
		nome: z.string().nonempty("Inserisci un nome valido"),
		telefono: z.string().nonempty("Inserisci un numero di telefono"),
	});
	const [value, setValue] = useLocalStorage<UserContattoData>(
		"infoalloggi-user-contatto",
		{
			email: "",
			nome: "",
			telefono: "",
		},
	);

	type FromValues = z.infer<typeof schema>;
	const form = useZodForm(schema, {
		defaultValues: {
			...value,
			checkbox: false, // Honeypot field
			messaggio: "",
		},
	});

	const { mutate } = api.comunicazioni.sendContattoAnnuncioEmail.useMutation({
		onError: (error) => {
			console.error(error);
			toast.error("Errore durante l'invio dell'email", {
				id: "contatto",
			});
		},
		onMutate: () => {
			toast.loading("Invio in corso...", {
				id: "contatto",
			});
		},
		onSuccess: (data) => {
			setHasSent(true);
			form.reset();
			toast.success(
				"Email inviata correttamente, ti contatteremo al più presto",
				{
					id: "contatto",
				},
			);
			setValue({
				...data,
			});
		},
	});
	const onSubmit = (data: FromValues) => {
		mutate({
			...data,
			codice,
			telefono: data.telefono.replace(/\s/g, ""), // Remove spaces from phone number
		});
	};
	z.config(z.locales[locale]());

	return (
		<div className="mx-auto w-full">
			{hasSent ? (
				<div className="flex h-full w-full items-center justify-center pt-14">
					<div className="mx-auto max-w-lg space-y-3 text-center">
						<CheckCircle className="mx-auto size-20 text-green-600" />
						<h3 className="font-semibold text-4xl text-accent-foreground sm:text-5xl">
							Successo
						</h3>
						<p className="text-muted-foreground">Email inviata correttamente</p>
						<div className="flex flex-wrap items-center justify-center gap-3"></div>
					</div>
				</div>
			) : (
				<Form {...form}>
					<form
						className="space-y-8 px-0.5"
						onSubmit={form.handleSubmit(onSubmit)}
					>
						<FormField
							control={form.control}
							name="nome"
							render={({ field }) => (
								<FormItem>
									<div className="flex flex-wrap items-center gap-x-2">
										<FormLabel htmlFor="nome">{t.contact_form.nome}</FormLabel>
										<FormMessage />
									</div>
									<FormControl>
										<Input {...field} type="text" />
									</FormControl>
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="email"
							render={({ field }) => (
								<FormItem>
									<div className="flex flex-wrap items-center gap-x-2">
										<FormLabel htmlFor="email">
											{t.contact_form.email}
										</FormLabel>
										<FormMessage />
									</div>
									<FormControl>
										<Input {...field} type="email" />
									</FormControl>
								</FormItem>
							)}
						/>
						<FormField
							control={form.control}
							name="telefono"
							render={({ field }) => (
								<FormItem>
									<div className="flex flex-wrap items-center gap-x-2">
										<FormLabel htmlFor="telefono">
											{t.contact_form.telefono}
										</FormLabel>
										<FormMessage />
									</div>
									<FormControl>
										<PhoneInput {...field} id="telefono" />
									</FormControl>
								</FormItem>
							)}
						/>
						<FormField
							control={form.control}
							name="messaggio"
							render={({ field }) => (
								<FormItem>
									<div className="flex flex-wrap items-center gap-x-2">
										<FormLabel htmlFor="messaggio">
											{t.contact_form.messaggio}
										</FormLabel>
										<FormMessage />
									</div>
									<FormControl>
										<Textarea className="min-h-37.5" {...field} />
									</FormControl>
								</FormItem>
							)}
						/>
						<FormField
							control={form.control}
							name="checkbox"
							render={({ field }) => (
								<FormItem className="hidden">
									<div className="flex flex-wrap items-center gap-x-2">
										<FormLabel htmlFor="checkbox">Check Me</FormLabel>
										<FormMessage />
									</div>

									<FormControl>
										<Checkbox
											defaultChecked={field.value}
											id="checkbox"
											onCheckedChange={field.onChange}
										/>
									</FormControl>
								</FormItem>
							)}
						/>
						<button
							className="w-full rounded-lg bg-neutral-600 px-4 py-2 font-medium text-white duration-150 hover:bg-neutral-500 active:bg-neutral-600"
							type="submit"
						>
							{t.contact_form.invia}
						</button>
					</form>
				</Form>
			)}
		</div>
	);
};
