import { add, format, formatDuration, intervalToDuration } from "date-fns";
import { it } from "date-fns/locale";
import { CalendarIcon, Trash2 } from "lucide-react";
import { z } from "zod/v4";
import { Confirm } from "~/components/confirm";
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
} from "~/components/custom_ui/form";
import { Button } from "~/components/ui/button";
import { Calendar } from "~/components/ui/calendar";
import Input from "~/components/ui/input";
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "~/components/ui/popover";
import { cn } from "~/lib/utils";
import { useZodForm } from "~/lib/zodForm";
import { useTranslation } from "~/providers/I18nProvider";
import type { Rinnovi } from "~/schemas/public/Rinnovi";

const Schema = z.object({
	codice: z.string().min(4, "Il codice è obbligatorio"),
	decorrenza: z.date(),
	scadenza: z.date(),
	gestionale_id: z.string().nullable(),
});

type FormValues = z.infer<typeof Schema>;

export const FormRinnovo = ({
	initialData,
	onSubmit,
	onDelete,
}: {
	initialData?: Rinnovi;
	onSubmit: (fields: FormValues) => void;
	onDelete?: () => void;
}) => {
	const { locale, t } = useTranslation();

	z.config(z.locales[locale]());
	const defaultValues: FormValues = initialData
		? {
				codice: initialData.codice,
				decorrenza: initialData.decorrenza,
				scadenza: initialData.scadenza,
				gestionale_id: initialData.gestionale_id,
			}
		: {
				codice: "",
				decorrenza: new Date(),
				scadenza: new Date(),
				gestionale_id: null,
			};
	const form = useZodForm(Schema, {
		defaultValues: defaultValues,
	});

	const [decorrenza, scadenza] = form.watch(["decorrenza", "scadenza"]);

	return (
		<Form {...form}>
			<form className="space-y-8 px-0.5" onSubmit={form.handleSubmit(onSubmit)}>
				<FormField
					control={form.control}
					name="codice"
					render={({ field }) => (
						<FormItem>
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="codice">Codice</FormLabel>
								<FormMessage />
							</div>
							<FormControl>
								<Input placeholder="" {...field} id="codice" />
							</FormControl>
						</FormItem>
					)}
				/>
				<FormField
					control={form.control}
					name="decorrenza"
					render={({ field }) => (
						<FormItem className="flex w-full flex-col">
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="decorrenza">Decorrenza</FormLabel>
								<FormMessage />
							</div>

							<Popover>
								<PopoverTrigger asChild>
									<FormControl>
										<Button
											className={cn(
												"h-10 w-full bg-card pl-3 text-left font-medium",
												!field.value && "text-muted-foreground",
												"rounded-lg border border-neutral-300 shadow-xs outline-hidden file:border-0 file:bg-transparent file:font-medium file:text-sm disabled:cursor-not-allowed disabled:opacity-50 dark:focus:border-transparent",
											)}
											id="decorrenza"
											variant={"outline"}
										>
											{field.value ? (
												format(field.value, "PPP", {
													locale: it,
												})
											) : (
												<span>{t.anagrafica.scegli_data}</span>
											)}
											<CalendarIcon className="ml-auto size-4 opacity-50" />
										</Button>
									</FormControl>
								</PopoverTrigger>
								<PopoverContent align="end" className="w-auto p-0">
									<Calendar
										autoFocus
										captionLayout="dropdown"
										defaultMonth={field.value || new Date()}
										endMonth={new Date(2050, 12)}
										locale={it}
										mode="single"
										onSelect={field.onChange}
										selected={field.value || undefined}
									/>
								</PopoverContent>
							</Popover>
						</FormItem>
					)}
				/>
				<FormField
					control={form.control}
					name="scadenza"
					render={({ field }) => (
						<FormItem className="flex w-full flex-col">
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="scadenza">Scadenza</FormLabel>
								<FormMessage />
							</div>

							<Popover>
								<PopoverTrigger asChild>
									<FormControl>
										<Button
											className={cn(
												"h-10 w-full bg-card pl-3 text-left font-medium",
												!field.value && "text-muted-foreground",
												"rounded-lg border border-neutral-300 shadow-xs outline-hidden file:border-0 file:bg-transparent file:font-medium file:text-sm disabled:cursor-not-allowed disabled:opacity-50 dark:focus:border-transparent",
											)}
											id="scadenza"
											variant={"outline"}
										>
											{field.value ? (
												format(field.value, "PPP", {
													locale: it,
												})
											) : (
												<span>{t.anagrafica.scegli_data}</span>
											)}
											<CalendarIcon className="ml-auto size-4 opacity-50" />
										</Button>
									</FormControl>
								</PopoverTrigger>
								<PopoverContent align="end" className="w-auto p-0">
									<Calendar
										autoFocus
										captionLayout="dropdown"
										defaultMonth={field.value || new Date()}
										endMonth={new Date(2050, 12)}
										locale={it}
										mode="single"
										onSelect={field.onChange}
										selected={field.value || undefined}
									/>
								</PopoverContent>
							</Popover>
						</FormItem>
					)}
				/>

				<p>
					Permanenza:{" "}
					{formatDuration(
						intervalToDuration({
							start: new Date(decorrenza),
							end: add(new Date(scadenza), { days: 1 }),
						}),
						{ locale: it, format: ["years", "months", "days"] },
					)}
				</p>
				<p>
					Attenzione: un cambiamento nella permanenza andrà ad aggiornare
					automaticamente l'ordine associato se non ancora pagato.
				</p>

				<FormField
					control={form.control}
					name="gestionale_id"
					render={({ field }) => (
						<FormItem>
							<div className="flex flex-wrap items-center gap-x-2">
								<FormLabel htmlFor="gestionale_id">Gestionale ID</FormLabel>
								<FormMessage />
							</div>
							<FormControl>
								<Input
									placeholder=""
									{...field}
									id="gestionale_id"
									value={field.value || undefined}
								/>
							</FormControl>
						</FormItem>
					)}
				/>
				<div className="flex items-center justify-end gap-2">
					{initialData && (
						<Confirm
							description="Sei sicuro di voler eliminare l'annuncio?"
							onConfirm={() => {
								if (onDelete) {
									onDelete();
								}
							}}
							title="Elimina annuncio"
						>
							<Button
								aria-label="Delete Annuncio"
								className="w-fit"
								variant="destructive"
							>
								<Trash2 />
								<span>Elimina</span>
							</Button>
						</Confirm>
					)}

					<Button type="submit">Salva</Button>
				</div>
			</form>
		</Form>
	);
};
