"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { updateOrder, updateOrderItem, deleteOrderItem } from "@/actions/orders/update-order"; import { AdminInput, AdminTextInput, AdminTextarea, useToast, AdminButton } from "./design-system"; type OrderItem = { id: string; product_id: string; quantity: number; price: number; products: { name: string } | null; }; type Order = { id: string; customer_name: string; customer_email: string | null; customer_phone: string | null; stop_id: string | null; status: string; subtotal: number; discount_amount: number; tax_amount: number | null; tax_rate: number | null; tax_source?: string | null; tax_location: string | null; internal_notes: string | null; discount_reason: string | null; pickup_complete: boolean; pickup_completed_at: string | null; pickup_completed_by: string | null; created_at: string; stops: { city: string; state: string; date: string } | null; order_items: OrderItem[]; }; type OrderEditFormProps = { order: Order; brandId: string | null; }; type EditableItem = { id: string; product_id: string; quantity: number; price: number; productName: string; removed: boolean; }; function formatCurrency(amount: number) { return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount); } export default function OrderEditForm({ order, brandId }: OrderEditFormProps) { const router = useRouter(); const { success: showSuccess, error: showError } = useToast(); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [saved, setSaved] = useState(false); const [customer_name, setCustomer_name] = useState(order.customer_name); const [customer_email, setCustomer_email] = useState(order.customer_email ?? ""); const [customer_phone, setCustomer_phone] = useState(order.customer_phone ?? ""); const [discount_amount, setDiscount_amount] = useState(order.discount_amount ?? 0); const [discount_reason, setDiscount_reason] = useState(order.discount_reason ?? ""); const [internal_notes, setInternal_notes] = useState(order.internal_notes ?? ""); const [status, setStatus] = useState(order.status); const [pickup_complete, setPickup_complete] = useState(order.pickup_complete); const [items, setItems] = useState( order.order_items.map((item) => ({ id: item.id, product_id: item.product_id, quantity: item.quantity, price: Number(item.price), productName: item.products?.name ?? "Unknown", removed: false, })) ); const visibleItems = items.filter((i) => !i.removed); const subtotal = visibleItems.reduce( (sum, i) => sum + Number(i.price) * i.quantity, 0 ); const total = Math.max(0, subtotal - discount_amount); // Validation const [fieldErrors, setFieldErrors] = useState>({}); function validateForm(): boolean { const errors: Record = {}; if (!customer_name.trim()) { errors.customer_name = "Customer name is required"; } if (discount_amount < 0) { errors.discount_amount = "Discount cannot be negative"; } setFieldErrors(errors); return Object.keys(errors).length === 0; } function updateItem(id: string, field: "quantity" | "price", value: number) { setItems((prev) => prev.map((i) => (i.id === id ? { ...i, [field]: value } : i)) ); // Clear error for the field when changed setFieldErrors((prev) => { const next = { ...prev }; delete next[field]; return next; }); } function removeItem(id: string) { setItems((prev) => prev.map((i) => (i.id === id ? { ...i, removed: true } : i)) ); } async function handleSave() { if (!validateForm()) { showError("Validation failed", "Please fix the errors below"); return; } setSaving(true); setError(null); setSaved(false); const toSave = items.filter((i) => !i.removed); const toRemove = items.filter((i) => i.removed); try { for (const item of toRemove) { const result = await deleteOrderItem(item.id); if (!result.success) { showError("Failed to remove item", result.error ?? "Please try again"); setSaving(false); return; } } for (const item of toSave) { const orig = order.order_items.find((o) => o.id === item.id); if (!orig) continue; if ( Number(orig.quantity) !== item.quantity || Number(orig.price) !== item.price ) { const result = await updateOrderItem(item.id, { quantity: item.quantity, price: Number(item.price), }); if (!result.success) { showError("Failed to update item", result.error ?? "Please try again"); setSaving(false); return; } } } const result = await updateOrder(order.id, brandId, { customer_name, customer_email: customer_email || null, customer_phone: customer_phone || null, discount_amount, discount_reason: discount_reason || null, internal_notes: internal_notes || null, status, pickup_complete, pickup_completed_at: pickup_complete ? new Date().toISOString() : null, subtotal, }); if (!result.success) { showError("Failed to save", result.error ?? "Please try again"); setSaving(false); return; } showSuccess("Order updated", "Changes have been saved"); setSaved(true); setSaving(false); router.refresh(); } catch (err) { showError("Network error", "Please check your connection and try again"); setSaving(false); } } return (
{error && (
{error}
)} {/* Order items */}

Order Items ({visibleItems.length})

{visibleItems.length === 0 ? (

No items

) : (
{visibleItems.map((item) => (

{item.productName}

updateItem(item.id, "quantity", Number(e.target.value)) } className="ha-field-input ha-field-input-mono" />
$ updateItem(item.id, "price", Number(e.target.value)) } className="ha-field-input ha-field-input-mono pl-8 pr-3" />

{formatCurrency(Number(item.price) * item.quantity)}

))}
)}
{/* Pricing */}
$ setDiscount_amount(Number(e.target.value))} className="ha-field-input ha-field-input-mono pl-8 pr-3" style={ fieldErrors.discount_amount ? { borderColor: "var(--admin-danger)", backgroundColor: "var(--admin-danger-soft)" } : undefined } />
{fieldErrors.discount_amount && (

{fieldErrors.discount_amount}

)}
setDiscount_reason(e.target.value)} placeholder="Optional" className="ha-field-input" />
Total {formatCurrency(subtotal + Number(order.tax_amount ?? 0) - discount_amount)}
{/* Customer fields */}
{ setCustomer_name(e.target.value); setFieldErrors((prev) => { const next = { ...prev }; delete next.customer_name; return next; }); }} className="ha-field-input" style={ fieldErrors.customer_name ? { borderColor: "var(--admin-danger)", backgroundColor: "var(--admin-danger-soft)" } : undefined } /> {fieldErrors.customer_name && (

{fieldErrors.customer_name}

)}
setCustomer_email(e.target.value)} /> setCustomer_phone(e.target.value)} />
{/* Status & pickup */}
{["pending", "confirmed", "cancelled"].map((s) => ( ))}
{/* Internal notes */} setInternal_notes(e.target.value)} rows={2} placeholder="Private notes for staff..." /> {saving ? "Saving..." : "Save Changes"}
); }