"use client"; import { useState, useEffect } from "react"; import { Dialog, DialogContent, DialogHeader, DialogTitle, } 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 { toast } from "sonner"; import type { Customer } from "@/lib/types"; interface CustomerDialogProps { open: boolean; onOpenChange: (open: boolean) => void; customer?: Customer | null; onSaved: () => void; } export function CustomerDialog({ open, onOpenChange, customer, onSaved, }: CustomerDialogProps) { const [loading, setLoading] = useState(false); const [form, setForm] = useState({ name: "", code: "", email: "", phone: "", address: "", contact_person: "", notes: "", }); useEffect(() => { if (customer) { setForm({ name: customer.name || "", code: customer.code || "", email: customer.email || "", phone: customer.phone || "", address: customer.address || "", contact_person: customer.contact_person || "", notes: customer.notes || "", }); } else { setForm({ name: "", code: "", email: "", phone: "", address: "", contact_person: "", notes: "", }); } }, [customer, open]); async function handleSubmit(e: React.FormEvent) { e.preventDefault(); if (!form.name || !form.code) { toast.error("Name and code are required"); return; } setLoading(true); try { const url = customer ? `/api/customers/${customer.id}` : "/api/customers"; const res = await fetch(url, { method: customer ? "PUT" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(form), }); if (!res.ok) { const err = await res.json(); throw new Error(err.error || "Failed to save"); } toast.success(customer ? "Customer updated" : "Customer created"); onSaved(); onOpenChange(false); } catch (err) { toast.error(err instanceof Error ? err.message : "Failed to save customer"); } finally { setLoading(false); } } return ( {customer ? "Edit Customer" : "Add Customer"}
setForm({ ...form, name: e.target.value })} placeholder="Acme Electronics" required />
setForm({ ...form, code: e.target.value.toUpperCase() })} placeholder="ACME" className="font-mono uppercase" required />
setForm({ ...form, email: e.target.value })} placeholder="orders@acme.com" />
setForm({ ...form, phone: e.target.value })} placeholder="+1 555-0123" />
setForm({ ...form, contact_person: e.target.value })} placeholder="John Doe" />