import { useEffect } from "react";
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 { MultiSelect, UnpackOptions } from "~/components/custom_ui/multiselect";
import { Textarea } from "~/components/custom_ui/textarea";
import { Button } from "~/components/ui/button";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "~/components/ui/select";
import { Switch } from "~/components/ui/switch";
import { useZodForm } from "~/lib/zodForm";
import type {
	Prezziario,
	PrezziarioIdprezziario,
} from "~/schemas/public/Prezziario";
import { api } from "~/utils/api";

type FormPrezzoProps = {
	initialValues: Prezziario | null;
	submitMutation: (values: Omit<Prezziario, "nome" | "descrizione">) => void;
};
export const FormPrezzo = ({
	initialValues,
	submitMutation,
}: FormPrezzoProps) => {
	const { data: stringhe_condizioni } =
		api.settings.getStringheCondizioni.useQuery();

	const stringhe_condizioni_options = [
		"",
		...(stringhe_condizioni
			? stringhe_condizioni.map((v) => String(v.stinga_id))
			: []),
	];
	const PrezzoSchema = z
		.object({
			desc_en: z.string(),
			desc_it: z.string(),
			idprezziario: z.custom<PrezziarioIdprezziario>(),
			isAcconto: z.boolean(),
			isActive: z.boolean(),
			isConsulenza: z.boolean(),
			isSaldo: z.boolean(),
			isStabile: z.boolean(),
			isTransitorio: z.boolean(),
			nome_en: z.string(),
			nome_it: z.string(),
			prezzo_cent: z.number().min(0),
			sconto: z.number().min(0).max(100),
			testo_condizioni: z.string().nullable(),
		})
		.superRefine(({ testo_condizioni }, ctx) => {
			if (testo_condizioni) {
				if (
					stringhe_condizioni_options.length > 0 &&
					!stringhe_condizioni_options.includes(testo_condizioni)
				) {
					console.log("testo_condizioni", testo_condizioni);
					console.log(
						"stringhe_condizioni_options",
						stringhe_condizioni_options,
					);

					ctx.addIssue({
						code: "custom",
						input: testo_condizioni,
						message: "Testo condizioni non valido",
						path: ["testo_condizioni"],
					});
				}
			}
		});

	type PrezzoFormValues = z.infer<typeof PrezzoSchema>;

	// This can come from your database or API.
	const defaultValues: PrezzoFormValues = initialValues || {
		desc_en: "",
		desc_it: "",
		idprezziario: "" as PrezziarioIdprezziario,
		isAcconto: false,
		isActive: false,
		isConsulenza: false,
		isSaldo: false,
		isStabile: false,
		isTransitorio: false,
		nome_en: "",
		nome_it: "",
		prezzo_cent: 0,
		sconto: 0,
		testo_condizioni: "",
	};

	z.config(z.locales.it());

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

	function onSubmit(fields: PrezzoFormValues) {
		submitMutation({
			...fields,
			testo_condizioni: fields.testo_condizioni || null,
		});
	}

	const { watch } = form;

	useEffect(() => {
		const subscription = watch((value, { name, type }) =>
			console.log(value, name, type),
		);
		return () => subscription.unsubscribe();
	}, [watch]);

	const scontoWch = watch(["sconto", "prezzo_cent"]);

	return (
		<>
			<Form {...form}>
				<form
					className="space-y-4 px-0.5"
					onSubmit={form.handleSubmit(onSubmit)}
				>
					<FormField
						control={form.control}
						name="idprezziario"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="idprezziario">Codice</FormLabel>
									<FormMessage />
								</div>
								<FormControl>
									<Input
										placeholder=""
										{...field}
										disabled={initialValues != null}
										id="idprezziario"
									/>
								</FormControl>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="nome_it"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="nome_it">Nome IT</FormLabel>
									<FormMessage />
								</div>
								<FormControl>
									<Input placeholder="" {...field} id="nome_it" />
								</FormControl>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="desc_it"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel
										className="text-base font-medium"
										htmlFor="desc_it"
									>
										Descrizione IT
									</FormLabel>
									<FormMessage />
								</div>
								<FormControl>
									<Textarea className="min-h-[150px]" {...field} id="desc_it" />
								</FormControl>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="nome_en"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="nome_en">Nome EN</FormLabel>
									<FormMessage />
								</div>
								<FormControl>
									<Input placeholder="" {...field} id="nome_en" />
								</FormControl>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="desc_en"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel
										className="text-base font-medium"
										htmlFor="desc_en"
									>
										Descrizione EN
									</FormLabel>
									<FormMessage />
								</div>
								<FormControl>
									<Textarea className="min-h-[150px]" {...field} id="desc_en" />
								</FormControl>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="prezzo_cent"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="prezzo">Prezzo</FormLabel>
									<FormMessage />
								</div>
								<FormControl>
									<Input
										{...field}
										id="prezzo"
										onChange={(v) => {
											field.onChange(parseFloat(v.target.value) * 100);
										}}
										step={0.01}
										type="number"
										value={Number(field.value) / 100}
									/>
								</FormControl>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="isAcconto"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="isAcconto">Acconto</FormLabel>
									<FormControl>
										<Switch
											checked={field.value}
											className="data-[state=checked]:bg-neutral-700"
											id="isAcconto"
											onCheckedChange={field.onChange}
										/>
									</FormControl>
									<FormMessage />
								</div>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="isSaldo"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="isSaldo">Saldo</FormLabel>
									<FormControl>
										<Switch
											checked={field.value}
											className="data-[state=checked]:bg-neutral-700"
											id="isSaldo"
											onCheckedChange={field.onChange}
										/>
									</FormControl>
									<FormMessage />
								</div>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="isConsulenza"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="isConsulenza">Consulenza</FormLabel>
									<FormControl>
										<Switch
											checked={field.value}
											className="data-[state=checked]:bg-neutral-700"
											id="isConsulenza"
											onCheckedChange={field.onChange}
										/>
									</FormControl>
									<FormMessage />
								</div>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="isTransitorio"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="isTransitorio">Transitorio</FormLabel>
									<FormControl>
										<Switch
											checked={field.value}
											className="data-[state=checked]:bg-neutral-700"
											id="isTransitorio"
											onCheckedChange={field.onChange}
										/>
									</FormControl>
									<FormMessage />
								</div>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="isStabile"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="isStabile">Stabile</FormLabel>
									<FormControl>
										<Switch
											checked={field.value}
											className="data-[state=checked]:bg-neutral-700"
											id="isStabile"
											onCheckedChange={field.onChange}
										/>
									</FormControl>
									<FormMessage />
								</div>
							</FormItem>
						)}
					/>

					<FormField
						control={form.control}
						name="testo_condizioni"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel
										className="text-base font-medium"
										htmlFor="select-testo-condizioni"
									>
										ID Testo Condizioni
									</FormLabel>
									<FormMessage />
								</div>

								<MultiSelect
									defaultValue={
										field.value
											? { label: field.value, value: field.value }
											: {
													label: "",
													value: "",
												}
									}
									elementId="select-testo-condizioni"
									elementName="testo_condizioni"
									isMulti={false}
									onValueChange={async (value) => {
										if (value.value === "") {
											field.onChange(undefined);
										} else {
											field.onChange(
												stringhe_condizioni_options[
													Number.parseInt(value.value)
												],
											);
										}

										await form.trigger("testo_condizioni");
									}}
									options={UnpackOptions({
										options: stringhe_condizioni_options,
									})}
									placeholder="Seleziona..."
								/>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="isActive"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="isActive">Attivo</FormLabel>
									<FormControl>
										<Switch
											checked={field.value}
											className="data-[state=checked]:bg-neutral-700"
											id="isActive"
											onCheckedChange={field.onChange}
										/>
									</FormControl>
									<FormMessage />
								</div>
							</FormItem>
						)}
					/>
					<FormField
						control={form.control}
						name="sconto"
						render={({ field }) => (
							<FormItem>
								<div className="flex flex-wrap items-center gap-x-2">
									<FormLabel htmlFor="sconto">Sconto</FormLabel>
									<FormControl>
										<Select
											defaultValue={String(field.value)}
											name="sconto"
											onValueChange={(value) => {
												field.onChange(Number.parseInt(value));
											}}
										>
											<SelectTrigger className="w-[180px]">
												<SelectValue placeholder="Sconto" />
											</SelectTrigger>
											<SelectContent>
												{[
													0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65,
													70, 75, 80, 85, 90, 95, 100,
												].map((v) => {
													return (
														<SelectItem key={v} value={String(v)}>
															{v}%
														</SelectItem>
													);
												})}
											</SelectContent>
										</Select>
									</FormControl>
									<FormMessage />
								</div>
							</FormItem>
						)}
					/>
					{scontoWch && scontoWch[0] !== 0 && (
						<span className="text-sm text-gray-500">
							Prezzo scontato:{" "}
							{(((1 - scontoWch[0] / 100) * scontoWch[1]) / 100).toFixed(2)}€
						</span>
					)}

					<div className="flex flex-row gap-4">
						<Button type="submit">
							{initialValues ? "Aggiorna" : "Crea Prezzo"}
						</Button>
					</div>
				</form>
			</Form>
		</>
	);
};
