"use client"; import { useActionState, useEffect, useRef, useState, useTransition } from "react"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"; import { Select } from "@/components/ui/select"; import { Combobox } from "@/components/ui/combobox"; import { createDeliveryNote, updateDeliveryNote, type ActionResult } from "@/actions/delivery-notes"; import { toast } from "sonner"; import type { Customer, DeliveryNote } from "@/lib/types"; import { DELIVERY_STATUSES, TANK_OPTIONS } from "@/lib/types"; import { RefreshCw } from "lucide-react"; const initial: ActionResult = { ok: false, error: "" }; interface Props { customers: Customer[]; note?: DeliveryNote; customerName?: string; preselectedCustomerId?: string; } function todayISO() { return new Date().toISOString().slice(0, 10); } export function DeliveryNoteForm({ customers, note, customerName, preselectedCustomerId }: Props) { const router = useRouter(); const isEdit = !!note; const boundAction = isEdit ? updateDeliveryNote.bind(null, note!.id) : createDeliveryNote; const [state, formAction, pending] = useActionState(boundAction, initial); const formRef = useRef(null); const [number, setNumber] = useState(note?.number || ""); const [date, setDate] = useState((note?.date || "").slice(0, 10) || todayISO()); const [customerId, setCustomerId] = useState(note?.customer || preselectedCustomerId || ""); const [qty, setQty] = useState(note?.qty_litres_supplied ?? ""); const [price, setPrice] = useState(note?.price_per_litre ?? ""); const [total, setTotal] = useState(note?.total_value ?? ""); const [source, setSource] = useState(note?.pricing_source || ""); const [autoFilled, setAutoFilled] = useState(false); const [tank, setTank] = useState(note?.plant_dispensing || "Plant 1"); const [, startTransition] = useTransition(); // Auto-fill price when customer/date change useEffect(() => { if (isEdit) return; if (!customerId || !date) return; startTransition(async () => { try { const res = await fetch(`/api/delivery-notes/price?customer=${customerId}&date=${date}`); if (res.ok) { const data = await res.json(); if (data.price) { setPrice(data.price); setSource(data.source || ""); setAutoFilled(true); if (qty) setTotal(Number((data.price * Number(qty)).toFixed(2))); } } } catch {} }); }, [customerId, date, isEdit, qty]); // Recompute total on qty/price change useEffect(() => { if (qty && price) { setTotal(Number((Number(qty) * Number(price)).toFixed(2))); } }, [qty, price]); // Auto-suggest next note number — called by the "Auto-Number" button, not on mount. function autoNumber() { if (isEdit) return; startTransition(async () => { try { const res = await fetch("/api/delivery-notes/next-number"); if (res.ok) { const data = await res.json(); if (data.number) setNumber(data.number); } } catch {} }); } useEffect(() => { if (state.ok) { toast.success(isEdit ? "Delivery note updated" : "Delivery note created"); if (!isEdit) { router.push("/delivery-notes"); } else { router.push(`/delivery-notes/${note!.id}`); } } else if (state.error) { toast.error(state.error); } }, [state, isEdit, router, note]); const customerItems = customers.map((c) => ({ value: c.id, label: c.name, hint: c.email || c.contact_number || undefined, })); return ( {isEdit ? `Edit ${note!.number}` : "Add delivery note"}
setNumber(e.target.value)} required placeholder="e.g. 0001" className="font-mono" /> {!isEdit && ( )}
setDate(e.target.value)} max={todayISO()} required />
setQty(e.target.value === "" ? "" : Number(e.target.value))} required />
{ setPrice(e.target.value === "" ? "" : Number(e.target.value)); setAutoFilled(false); }} /> {autoFilled && source && (

auto-filled from {source} pricing

)}
setTotal(e.target.value === "" ? "" : Number(e.target.value))} />