"use client";

import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/components/ui/use-toast";
import { updatePrintComments } from "@/server/actions/printJobs";
import { useDebouncedCallback } from "use-debounce";

interface EditCommentsProps {
	defaultValue: string | null;
	jobId: string;
	disabled?: boolean;
}
export function EditComments(props: EditCommentsProps) {
	const { defaultValue, jobId, disabled } = props;
	const { toast } = useToast();

	const debounced = useDebouncedCallback(async (value) => {
		try {
			await updatePrintComments(jobId, value);
			toast({
				description: "Anmerkungen wurden gespeichert.",
			});
		} catch (error) {
			if (error instanceof Error) {
				toast({
					description: error.message,
					variant: "destructive",
				});
			} else {
				toast({
					description: "Ein unbekannter Fehler ist aufgetreten.",
					variant: "destructive",
				});
			}
		}
	}, 1000);

	return (
		<div className="flex flex-col gap-2">
			<Label>Anmerkungen</Label>
			<Textarea
				placeholder="Anmerkungen"
				disabled={disabled}
				defaultValue={defaultValue ?? ""}
				onChange={(e) => debounced(e.target.value)}
			/>
		</div>
	);
}
