"use client"; import { useState } from "react"; import { useTranslations } from "next-intl"; import { toast } from "sonner"; 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { GROCERY_CATEGORIES } from "@/lib/grocery-categories"; export type PantryItem = { id: string; rawName: string; quantity: string | null; unit: string | null; notes: string | null; aisle: string | null; expiresAt: string | null; }; const OTHER_VALUE = "__other__"; function categoryLabel(value: string, tShopping: (key: string) => string): string { return value === OTHER_VALUE ? tShopping("aisleOther") : tShopping(`categories.${value}`); } export function PantryItemDialog({ item, open, onOpenChange, onSaved, }: { item: PantryItem; open: boolean; onOpenChange: (open: boolean) => void; onSaved: (updated: PantryItem) => void; }) { const t = useTranslations("pantry"); const tShopping = useTranslations("shoppingLists"); const tCommon = useTranslations("common"); const [rawName, setRawName] = useState(item.rawName); const [quantity, setQuantity] = useState(item.quantity ?? ""); const [unit, setUnit] = useState(item.unit ?? ""); const [aisle, setAisle] = useState(item.aisle ?? OTHER_VALUE); const [notes, setNotes] = useState(item.notes ?? ""); const [expiresAt, setExpiresAt] = useState(item.expiresAt ? item.expiresAt.slice(0, 10) : ""); const [saving, setSaving] = useState(false); async function handleSave() { if (!rawName.trim()) return; setSaving(true); try { const res = await fetch(`/api/v1/pantry/${item.id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rawName: rawName.trim(), quantity: quantity.trim() || null, unit: unit.trim() || null, aisle: aisle === OTHER_VALUE ? null : aisle, notes: notes.trim() || null, expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null, }), }); if (!res.ok) { toast.error(t("editFailed")); return; } toast.success(t("editSaved")); onSaved({ id: item.id, rawName: rawName.trim(), quantity: quantity.trim() || null, unit: unit.trim() || null, aisle: aisle === OTHER_VALUE ? null : aisle, notes: notes.trim() || null, expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null, }); onOpenChange(false); } finally { setSaving(false); } } return ( {t("editDialogTitle")}
setRawName(e.target.value)} />
setQuantity(e.target.value)} />
setUnit(e.target.value)} />
setExpiresAt(e.target.value)} />