// components/gifts/category-modal.tsx import React, { useEffect } from "react"; import { useForm } from "react-hook-form"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { useGifts } from "@/context/gift-context"; import { GiftCategory, GiftCategoryCreate, GiftCategoryUpdate, } from "@/client/types.gen"; import { Loader2 } from "lucide-react"; import { useAuth } from "@/context/auth-context"; interface CategoryModalProps { isOpen: boolean; onClose: () => void; categoryId?: string; eventId: string; } export function CategoryModal({ isOpen, onClose, categoryId, eventId, }: CategoryModalProps) { const { category, createCategory, updateCategory, fetchCategoryById, isLoadingCategory, } = useGifts(); const { user } = useAuth(); const isEditMode = Boolean(categoryId); const { register, handleSubmit, reset, formState: { errors, isSubmitting }, } = useForm(); // Load category data when editing useEffect(() => { if (isEditMode && categoryId) { fetchCategoryById(categoryId, eventId); } }, [isEditMode, categoryId, eventId, fetchCategoryById]); // Reset form when modal opens or category changes useEffect(() => { if (isOpen) { if (isEditMode && category) { reset({ name: category.name, description: category.description, icon: category.icon, color: category.color, }); } else { reset({ name: "", description: "", icon: "", color: "#4f46e5", // Default color }); } } }, [isOpen, category, isEditMode, reset]); const onSubmit = async (data: GiftCategoryCreate | GiftCategoryUpdate) => { try { if (isEditMode && categoryId) { await updateCategory(categoryId, data as GiftCategoryUpdate, eventId); } else { const createData = { ...data, created_by: user?.id, // This should be replaced with the actual user ID } as GiftCategoryCreate; await createCategory(createData); } onClose(); } catch (error) { console.error("Error saving category:", error); } }; return ( {isEditMode ? "Edit Category" : "Add Category"} {isLoadingCategory && isEditMode ? (
) : (
{errors.name && (

{errors.name.message}

)}