"use client";
import { DeletePrinterDialog } from "@/app/admin/printers/dialogs/delete-printer";
import { Button } from "@/components/ui/button";
import { DialogClose } from "@/components/ui/dialog";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/components/ui/use-toast";
import { createPrinter, updatePrinter } from "@/server/actions/printers";
import type { InferResultType } from "@/utils/drizzle";
import { zodResolver } from "@hookform/resolvers/zod";
import { SaveIcon, XCircleIcon } from "lucide-react";
import { useForm } from "react-hook-form";
import { z } from "zod";

export const formSchema = z.object({
	name: z
		.string()
		.min(2, {
			message: "Der Name muss mindestens 2 Zeichen lang sein.",
		})
		.max(50),
	description: z
		.string()
		.min(2, {
			message: "Die Beschreibung muss mindestens 2 Zeichen lang sein.",
		})
		.max(50),
	status: z.coerce.number().int().min(0).max(1),
});

interface PrinterFormProps {
	printer?: InferResultType<"printers">;
	setOpen: (state: boolean) => void;
}

export function PrinterForm(props: PrinterFormProps) {
	const { printer, setOpen } = props;
	const { toast } = useToast();

	const form = useForm<z.infer<typeof formSchema>>({
		resolver: zodResolver(formSchema),
		defaultValues: {
			name: printer?.name ?? "",
			description: printer?.description ?? "",
			status: printer?.status ?? 0,
		},
	});

	// 2. Define a submit handler.
	async function onSubmit(values: z.infer<typeof formSchema>) {
		// TODO: create or update
		if (printer) {
			toast({
				description: "Drucker wird aktualisiert...",
			});

			// Update
			try {
				await updatePrinter(printer.id, {
					description: values.description,
					name: values.name,
					status: values.status,
				});

				setOpen(false);

				toast({
					description: "Drucker wurde aktualisiert.",
					variant: "default",
				});
			} catch (error) {
				if (error instanceof Error) {
					toast({
						description: error.message,
						variant: "destructive",
					});
				} else {
					toast({
						description: "Ein unbekannter Fehler ist aufgetreten.",
						variant: "destructive",
					});
				}
			}
		} else {
			toast({
				description: "Drucker wird erstellt...",
				variant: "default",
			});

			// Create
			try {
				await createPrinter({
					description: values.description,
					name: values.name,
					status: values.status,
				});

				setOpen(false);

				toast({
					description: "Drucker wurde erstellt.",
					variant: "default",
				});
			} catch (error) {
				if (error instanceof Error) {
					toast({
						description: error.message,
						variant: "destructive",
					});
				} else {
					toast({
						description: "Ein unbekannter Fehler ist aufgetreten.",
						variant: "destructive",
					});
				}
			}
		}
	}

	return (
		<Form {...form}>
			<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
				<FormField
					control={form.control}
					name="name"
					render={({ field }) => (
						<FormItem>
							<FormLabel>Name</FormLabel>
							<FormControl>
								<Input placeholder="Anycubic Kobra 2 Pro" {...field} />
							</FormControl>
							<FormDescription>Bitte gib einen eindeutigen Namen für den Drucker ein.</FormDescription>
							<FormMessage />
						</FormItem>
					)}
				/>
				<FormField
					control={form.control}
					name="description"
					render={({ field }) => (
						<FormItem>
							<FormLabel>Beschreibung</FormLabel>
							<FormControl>
								<Input placeholder="80x80x80 Druckfläche, langsam" {...field} />
							</FormControl>
							<FormDescription>Füge eine kurze Beschreibung des Druckers hinzu.</FormDescription>
							<FormMessage />
						</FormItem>
					)}
				/>
				<FormField
					control={form.control}
					name="status"
					render={({ field }) => (
						<FormItem>
							<FormLabel>Status</FormLabel>
							<Select onValueChange={field.onChange} defaultValue={field.value.toString()}>
								<FormControl>
									<SelectTrigger>
										<SelectValue placeholder="Select a verified email to display" />
									</SelectTrigger>
								</FormControl>
								<SelectContent>
									<SelectItem value={"0"}>Verfügbar</SelectItem>
									<SelectItem value={"1"}>Außer Betrieb</SelectItem>
								</SelectContent>
							</Select>
							<FormDescription>Wähle den aktuellen Status des Druckers.</FormDescription>
							<FormMessage />
						</FormItem>
					)}
				/>
				<div className="flex justify-between items-center">
					{printer && <DeletePrinterDialog setOpen={setOpen} printerId={printer?.id} />}
					{!printer && (
						<DialogClose asChild>
							<Button variant="secondary" className="gap-2 flex items-center">
								<XCircleIcon className="w-4 h-4" />
								<span>Abbrechen</span>
							</Button>
						</DialogClose>
					)}
					<Button type="submit" className="gap-2 flex items-center">
						<SaveIcon className="w-4 h-4" />
						<span>Speichern</span>
					</Button>
				</div>
			</form>
		</Form>
	);
}
