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 { Product, ProductVariantRow } from '@/types'; type OptionInput = { name: string; values: string }; type Prices = { price: string; compare_at_price: string; stock: string }; const MAX_OPTIONS = 2; /** "250g, 500g, 250g" becomes ["250g", "500g"]. */ function choices(line: string): string[] { const seen = new Set(); return line .split(',') .map((value) => value.trim()) .filter((value) => { const key = value.toLowerCase(); if (value === '' || seen.has(key)) { return false; } seen.add(key); return true; }); } function comboKey(first: string, second: string | null): string { return `${first.toLowerCase()}|${(second ?? '').toLowerCase()}`; } /** * Options such as Size and Flavour, and a price and stock for every combination of their choices. * The inputs carry the names the server reads: options[i][name], variants[j][price] and so on. */ export default function VariantEditor({ product, enabled, onEnabledChange, errors, }: { product?: Product; enabled: boolean; onEnabledChange: (enabled: boolean) => void; errors: Record; }) { const [options, setOptions] = useState( product && product.options.length > 0 ? product.options : [{ name: '', values: '' }], ); const [prices, setPrices] = useState>(() => Object.fromEntries( (product?.variants ?? []).map((row: ProductVariantRow) => [ comboKey(row.option1, row.option2), { price: row.price, compare_at_price: row.compare_at_price ?? '', stock: String(row.stock), }, ]), ), ); const first = choices(options[0]?.values ?? ''); const second = options[1] ? choices(options[1].values) : []; const combinations: [string, string | null][] = first.flatMap((a) => second.length > 0 ? second.map((b): [string, string | null] => [a, b]) : [[a, null]], ); function setOption(index: number, field: keyof OptionInput, value: string) { setOptions((current) => current.map((option, i) => i === index ? { ...option, [field]: value } : option, ), ); } function setPrice(key: string, field: keyof Prices, value: string) { const empty: Prices = { price: '', compare_at_price: '', stock: '0' }; setPrices((current) => ({ ...current, [key]: { ...(current[key] ?? empty), [field]: value }, })); } /** Copy the first row's price and stock to every row. */ function fillAll() { const firstKey = combinations[0] ? comboKey(combinations[0][0], combinations[0][1]) : null; const source = firstKey ? prices[firstKey] : undefined; if (!source) { return; } setPrices((current) => { const next = { ...current }; for (const [a, b] of combinations) { next[comboKey(a, b)] = { ...source }; } return next; }); } const optionErrors = Object.entries(errors) .filter(([key]) => key === 'options' || key.startsWith('options.')) .map(([, message]) => message); const variantErrors = [ ...new Set( Object.entries(errors) .filter( ([key]) => key === 'variants' || key.startsWith('variants.'), ) .map(([, message]) => message), ), ]; return (
onEnabledChange(checked === true) } />

Such as sizes, colours or flavours, each with its own price and stock.

{enabled && ( <>
{options.map((option, index) => (
setOption( index, 'name', event.target.value, ) } placeholder={ index === 0 ? 'Size' : 'Flavour' } />
setOption( index, 'values', event.target.value, ) } placeholder={ index === 0 ? '250g, 500g' : 'Original, Pedas' } />
{index > 0 && ( )}
))} {options.length < MAX_OPTIONS && ( )} {optionErrors.map((message) => ( ))}
{combinations.length > 0 && (

Price and stock for each choice ( {combinations.length})

{combinations.length > 1 && ( )}
{combinations.map(([a, b], row) => { const key = comboKey(a, b); const value = prices[key]; const label = b ? `${a} / ${b}` : a; return ( ); })}
Choice Price (RM) Before discount Stock
{label} {b && ( )} setPrice( key, 'price', event.target .value, ) } placeholder="12.90" /> setPrice( key, 'compare_at_price', event.target .value, ) } placeholder="Optional" /> setPrice( key, 'stock', event.target .value, ) } />
{variantErrors.map((message) => ( ))}
)} )}
); }