"use client"; import type { MenuItemEntity } from "@/lib/types"; import { useState } from "react"; import type { ProductModalProps } from "./Manager.types"; export default function ProductModal({ product, onSave, onClose, }: ProductModalProps) { const isEdit = product !== null; const [form, setForm] = useState({ name: product?.name ?? "", price: product?.price ?? 0, imageUrl: product?.imageUrl ?? "", description: product?.description ?? "", available: product?.available ?? true, }); const [uploading, setUploading] = useState(false); const [uploadError, setUploadError] = useState(null); const inputCls = "text-foreground w-full rounded-xl border border-(--color-border) bg-white px-3 py-2 text-sm transition outline-none focus:border-(--color-primary) focus:ring-2 focus:ring-(--color-primary)/20"; const uploadImage = async (file: File) => { setUploading(true); setUploadError(null); try { const body = new FormData(); body.append("file", file); const res = await fetch("/api/file", { method: "POST", body, }); if (!res.ok) { throw new Error("Image upload failed."); } const raw = await res.text(); let filename = ""; try { const parsed = JSON.parse(raw.trim()); filename = parsed.filename || ""; } catch { const match = raw.match(/"filename"\s*:\s*"([^"]+)"/i); filename = match?.[1] || ""; } if (!filename) { throw new Error("No image filename received from server."); } setForm((prev) => ({ ...prev, imageUrl: filename })); } catch (error: any) { setUploadError(error?.message || "Unable to upload image."); } finally { setUploading(false); } }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (isEdit && product) { onSave({ ...form, id: product.id }); } else { onSave(form); } }; const handleFileChange = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; await uploadImage(file); }; const toDisplayUrl = (filename: string) => filename && !filename.startsWith("/") && !filename.startsWith("http") ? `/api/file/${filename}` : filename; const previewUrl = toDisplayUrl(form.imageUrl); return (

{isEdit ? "Edit item" : "Add new item"}

setForm({ ...form, name: e.target.value })} className={inputCls} placeholder="e.g. Black Coffee" />
setForm({ ...form, price: Number(e.target.value) }) } className={inputCls} placeholder="25000" />
{uploading && (

Uploading image...

)}
{previewUrl && (
Item image preview
)} {uploadError && (

{uploadError}

)}