"use client"; import { ChangeEvent, useState, useEffect } from "react"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Product } from "@/models/products"; import { Trash, PlusCircle } from "lucide-react"; import { toast } from "sonner"; interface Category { _id: string; name: string; } interface PricingTier { minQuantity: number; pricePerUnit: number; _id?: string; } interface ProductData { name: string; description: string; unitType: string; category: string; pricing: PricingTier[]; image: string | File | null; } interface ProductModalProps { open: boolean; onClose: () => void; onSave: (productData: ProductData) => void; productData: ProductData; categories: Category[]; editing: boolean; handleChange: ( e: ChangeEvent ) => void; setProductData: React.Dispatch>; } export const ProductModal = ({ open, onClose, onSave, productData, categories, editing, handleChange, setProductData, }: ProductModalProps) => { const [imagePreview, setImagePreview] = useState(null); const [newCategory, setNewCategory] = useState(""); const [imageDimensions, setImageDimensions] = useState({ width: 300, height: 200, }); useEffect(() => { if (productData?.pricing) { setProductData((prev) => ({ ...prev, tieredPricing: productData.pricing, })); } }, [productData.pricing]); useEffect(() => { if (productData.image && typeof productData.image === "string") { setImagePreview(productData.image); } }, [productData.image]); const handleImageChange = (e: ChangeEvent) => { const file = e.target.files?.[0]; if (file) { const image = new Image(); const objectUrl = URL.createObjectURL(file); image.onload = () => { const aspectRatio = image.naturalWidth / image.naturalHeight; let width = 300; let height = 200; if (aspectRatio > 1) { width = 300; height = 300 / aspectRatio; } else { height = 200; width = 200 * aspectRatio; } setProductData({ ...productData, image: file }); setImagePreview(objectUrl); setImageDimensions({ width, height }); }; image.src = objectUrl; } else { setProductData({ ...productData, image: null }); setImagePreview(null); } }; const handleSave = () => { onSave(productData); toast.success( editing ? "Product updated successfully!" : "Product added successfully!" ); onClose(); }; const handleTieredPricingChange = ( e: ChangeEvent, index: number ) => { const { name, valueAsNumber } = e.target; if (!productData.pricing) return; const updatedPricing = [...productData.pricing]; updatedPricing[index] = { ...updatedPricing[index], [name]: isNaN(valueAsNumber) ? 0 : valueAsNumber, // Ensure valid numbers }; setProductData((prev) => ({ ...prev, tieredPricing: updatedPricing, })); }; return ( {editing ? "Edit Product" : "Add Product"}
{/* Description */}