import { useMemo, useState } from "react"; import { Pressable, StyleSheet, Text, View } from "react-native"; import { Ionicons } from "@expo/vector-icons"; import { Button } from "@/components/ui/Button"; import { fonts, spacing } from "@/constants/theme"; import { useAppTheme } from "@/contexts/ThemeContext"; import { formatCurrency } from "@/lib/format"; import type { ReceiptLineItem } from "@/lib/receipt-parse"; export type ReceiptSplitSelection = { selectedItemIds: string[]; selectedSubtotal: number; allocatedTax: number; owedTotal: number; notes: string; }; type ReceiptItemSelectorProps = { items: ReceiptLineItem[]; subtotal: number | null; tax: number | null; total: number | null; onApply: (selection: ReceiptSplitSelection) => void; }; export function ReceiptItemSelector({ items, subtotal, tax, total, onApply, }: ReceiptItemSelectorProps) { const { colors } = useAppTheme(); const [selectedIds, setSelectedIds] = useState>( () => new Set(items.map((item) => item.id)), ); const calculation = useMemo(() => { const selected = items.filter((item) => selectedIds.has(item.id)); const selectedSubtotal = roundMoney( selected.reduce((sum, item) => sum + item.amount, 0), ); const receiptSubtotal = subtotal && subtotal > 0 ? subtotal : roundMoney(items.reduce((sum, item) => sum + item.amount, 0)); const knownTax = tax ?? (total && receiptSubtotal > 0 ? Math.max(0, roundMoney(total - receiptSubtotal)) : 0); const allocatedTax = receiptSubtotal > 0 ? roundMoney(knownTax * (selectedSubtotal / receiptSubtotal)) : 0; const owedTotal = roundMoney(selectedSubtotal + allocatedTax); const notes = [ "Receipt split", ...selected.map( (item) => `- ${item.name}: ${formatCurrency(item.amount)}`, ), `Selected subtotal: ${formatCurrency(selectedSubtotal)}`, `Allocated tax: ${formatCurrency(allocatedTax)}`, `Owed total: ${formatCurrency(owedTotal)}`, ].join("\n"); return { selected, selectedSubtotal, allocatedTax, owedTotal, notes }; }, [items, selectedIds, subtotal, tax, total]); if (items.length === 0) return null; const toggle = (id: string) => { setSelectedIds((current) => { const next = new Set(current); if (next.has(id)) next.delete(id); else next.add(id); return next; }); }; return ( Split receipt items Select what this person owes. Tax is split proportionally. {formatCurrency(calculation.owedTotal)} {items.map((item) => { const selected = selectedIds.has(item.id); return ( toggle(item.id)} style={({ pressed }) => [ styles.item, { borderColor: colors.borderGlass }, selected && { backgroundColor: colors.muted }, pressed && styles.pressed, ]} > {item.name} {formatCurrency(item.amount)} ); })}