import { Plus, X } from 'lucide-react'; import { useState } from 'react'; import InputError from '@/components/input-error'; import { Button } from '@/components/ui/button'; import { Checkbox } from '@/components/ui/checkbox'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import type { BundleChoice, Product } from '@/types'; type Row = { item: string; quantity: string }; const MAX_ITEMS = 10; const selectClass = 'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 md:text-sm'; /** * A bundle: other products of the store sold together at one price. * Its stock is not typed in; it follows the stock of what is inside. * The inputs carry the names the server reads: is_bundle, bundle_items[i][item] and bundle_items[i][quantity]. */ export default function BundleEditor({ product, choices, enabled, onEnabledChange, errors, }: { product?: Product; choices: BundleChoice[]; enabled: boolean; onEnabledChange: (enabled: boolean) => void; errors: Record; }) { const [rows, setRows] = useState( product && product.bundle_items.length > 0 ? product.bundle_items.map((row) => ({ item: row.item, quantity: String(row.quantity), })) : [{ item: '', quantity: '1' }], ); const byKey = new Map(choices.map((choice) => [choice.key, choice])); const filled = rows .map((row) => ({ choice: byKey.get(row.item), quantity: Math.max(1, Number(row.quantity) || 1), })) .filter((row) => row.choice !== undefined); // What the items cost bought one by one, and how many bundles their stock allows. const separately = filled.reduce( (sum, row) => sum + Number(row.choice!.price) * row.quantity, 0, ); const stock = filled.length > 0 ? Math.min( ...filled.map((row) => Math.floor(row.choice!.stock / row.quantity), ), ) : 0; function setRow(index: number, field: keyof Row, value: string) { setRows((current) => current.map((row, i) => i === index ? { ...row, [field]: value } : row, ), ); } const rowErrors = (index: number) => errors[`bundle_items.${index}.item`] ?? errors[`bundle_items.${index}.quantity`]; return (
onEnabledChange(checked === true) } />

Sell some of your products together at one price. The stock follows the products inside.

{enabled && ( <> {choices.length === 0 ? (

Add the products that go inside first. Then come back to make the bundle.

) : (

What is inside

{rows.map((row, index) => (
× setRow( index, 'quantity', event.target.value, ) } />
))} {rows.length < MAX_ITEMS && ( )} {filled.length > 0 && (

Bought one by one: RM{' '} {separately.toFixed(2)} · Bundles you can sell now: {stock}

)}
)} )}
); }