"use client" import { Card, CardContent } from "@/shared/components/ui/card" import { Separator } from "@/shared/components/ui/separator" import { formatCurrency, formatEnum } from "@/shared/utils/formatters" import { cn } from "@/shared/lib/utils" import { useBill } from "./bill-context" export function BillTotalsSummary() { const bill = useBill() if (!bill) return null const parts = bill.parts ?? [] const services = bill.services ?? [] const expenses = bill.expenses ?? [] const hasItems = parts.length > 0 || services.length > 0 || expenses.length > 0 if (!hasItems) return null function lineTotal(items: { quantity?: string | number; rate?: string | number }[]) { return items.reduce((sum, item) => { const qty = parseFloat(String(item.quantity ?? 0)) const rate = parseFloat(String(item.rate ?? 0)) return sum + (isNaN(qty) || isNaN(rate) ? 0 : qty * rate) }, 0) } const partsTotal = lineTotal(parts) const servicesTotal = lineTotal(services) const expensesTotal = lineTotal(expenses) // Use API-computed values when available, fall back to manual calc const subTotal = bill.sub_total ?? (partsTotal + servicesTotal + expensesTotal) const taxAmount = bill.tax_amount ?? 0 const discountAmount = bill.discount_amount_major ?? 0 const total = bill.total ?? subTotal const paymentsMade = bill.payments_made ?? 0 const balanceDue = bill.balance_due ?? total const discount = bill.discount_type return (
{parts.length > 0 && (
Parts ({parts.length}) {formatCurrency(partsTotal)}
)} {services.length > 0 && (
Services ({services.length}) {formatCurrency(servicesTotal)}
)} {expenses.length > 0 && (
Expenses ({expenses.length}) {formatCurrency(expensesTotal)}
)}
Subtotal {formatCurrency(subTotal)}
{discountAmount > 0 && (
Discount{discount && discount !== "no" ? ` (${formatEnum(discount)})` : ""} −{formatCurrency(discountAmount)}
)} {taxAmount > 0 && (
Tax{bill.tax?.name ? ` (${bill.tax.name})` : ""} {formatCurrency(taxAmount)}
)}
Total {formatCurrency(total)}
{paymentsMade > 0 && (
Payments Made −{formatCurrency(paymentsMade)}
)} {paymentsMade > 0 && ( <>
0 ? "text-destructive bg-destructive/5" : "text-emerald-700 bg-emerald-50 dark:bg-emerald-950/20", )}> Balance Due {formatCurrency(balanceDue)}
)}
) }