/* Selling something loose (rice by the kg, paraffin by the litre, fabric by the metre): type what the scale shows,
   in kg or grams, tap a usual amount, or type the money the customer wants to spend and the app works out how much. */
import { useState, type FormEvent } from 'react';
import { Scale } from 'lucide-react';
import { Modal } from './overlays';
import { Button, Input, cx } from './ui';
import { money, qty, toMinor } from '../lib';
import { useT } from '../i18n';

type Loose = { id: number; name: string; price: number; unit: string | null };

export default function ScaleDialog({ item, current, currency, onAdd, onClose }: {
    item: Loose | null; current: number | null; currency: string; onAdd: (quantity: number, worth: number | null) => void; onClose: () => void;
}) {
    const t = useT();
    const unit = item?.unit ?? 'kg';
    const isKg = unit === 'kg';
    const [mode, setMode] = useState<'amount' | 'money'>('amount');
    const [grams, setGrams] = useState(false);
    const [value, setValue] = useState(current ? qty(current) : '');
    const [worth, setWorth] = useState('');

    // what goes in the cart, in the item's unit (kg, L, m)
    const typed = Number(value.replace(',', '.'));
    const fromAmount = !value || Number.isNaN(typed) ? 0 : grams ? typed / 1000 : typed;
    const worthMinor = toMinor(worth) ?? 0;
    const fromMoney = item && item.price > 0 ? Math.round((worthMinor / item.price) * 1000) / 1000 : 0;
    const quantity = Math.round((mode === 'money' ? fromMoney : fromAmount) * 1000) / 1000;
    const chips = isKg ? [0.25, 0.5, 1, 2, 5] : [0.5, 1, 2, 5];
    // sold by money: the line is exactly what the customer pays (MWK 500), not a rounded weight times the price
    const submit = (e: FormEvent) => { e.preventDefault(); if (quantity > 0) onAdd(quantity, mode === 'money' ? worthMinor : null); };

    return (
        <Modal open={!!item} onClose={onClose} title={item?.name ?? ''} subtitle={item ? `${money(item.price, currency)} ${t('per')} ${unit}` : ''}>
            {item && (
                <form onSubmit={submit} className="space-y-4">
                    <div className="grid grid-cols-2 rounded-xl bg-line-2 p-1">
                        {(['amount', 'money'] as const).map((m) => (
                            <button key={m} type="button" onClick={() => setMode(m)} className={cx('rounded-lg py-2 text-sm font-bold', mode === m ? 'bg-white text-ink shadow-card' : 'text-muted')}>
                                {m === 'amount' ? (isKg ? t('Weight') : t('Amount')) : t('By money')}
                            </button>
                        ))}
                    </div>

                    {mode === 'amount' ? (
                        <div>
                            <div className="flex items-center gap-2 rounded-2xl border-2 border-line px-4 focus-within:border-brand">
                                <Scale className="size-5 text-muted" aria-hidden />
                                <input inputMode="decimal" autoFocus placeholder="0" value={value} onChange={(e) => setValue(e.target.value)}
                                    className="w-full min-w-0 bg-transparent py-3 text-3xl font-extrabold text-ink focus:outline-none" aria-label={t('How much')} />
                                {isKg ? (
                                    <div className="flex shrink-0 rounded-lg bg-line-2 p-0.5 text-sm font-bold">
                                        {[false, true].map((g) => (
                                            <button key={String(g)} type="button" onClick={() => setGrams(g)} className={cx('rounded-md px-2.5 py-1', grams === g ? 'bg-white text-ink shadow-card' : 'text-muted')}>{g ? 'g' : 'kg'}</button>
                                        ))}
                                    </div>
                                ) : <span className="text-lg font-bold text-muted">{unit}</span>}
                            </div>
                            <div className="mt-2 flex flex-wrap gap-1.5">
                                {chips.map((c) => (
                                    <button key={c} type="button" onClick={() => { setGrams(false); setValue(String(c)); }} className="rounded-full bg-line-2 px-3 py-1.5 text-sm font-bold text-ink-2">
                                        {c === 0.25 ? '¼' : c === 0.5 ? '½' : c} {unit}
                                    </button>
                                ))}
                            </div>
                        </div>
                    ) : (
                        <div>
                            <p className="mb-2 text-sm text-muted">{t('How much does the customer want to spend?')}</p>
                            <div className="flex items-center gap-2 rounded-2xl border-2 border-line px-4 focus-within:border-brand">
                                <span className="text-lg font-bold text-muted">{currency}</span>
                                <Input inputMode="decimal" autoFocus placeholder="0" value={worth} onChange={(e) => setWorth(e.target.value)} className="!border-0 !p-0 !text-3xl !font-extrabold !shadow-none !ring-0" />
                            </div>
                            <div className="mt-2 flex flex-wrap gap-1.5">
                                {[20000, 50000, 100000, 200000].map((m) => (
                                    <button key={m} type="button" onClick={() => setWorth(String(m / 100))} className="rounded-full bg-line-2 px-3 py-1.5 text-sm font-bold text-ink-2">{money(m, currency)}</button>
                                ))}
                            </div>
                            {fromMoney > 0 && <p className="mt-3 text-sm text-ink-2">{t('Weigh out')} <b className="text-ink">{isKg && fromMoney < 1 ? `${Math.round(fromMoney * 1000)} g` : `${qty(fromMoney)} ${unit}`}</b></p>}
                        </div>
                    )}

                    <Button type="submit" size="lg" className="w-full" disabled={quantity <= 0}>
                        {quantity > 0 ? `${t('Add')} ${qty(quantity)} ${unit} · ${money(mode === 'money' ? worthMinor : Math.round(quantity * item.price), currency)}` : t('Add')}
                    </Button>
                </form>
            )}
        </Modal>
    );
}
