/* Kaunjika: bale by bale. The bale on the table (how it is doing, whether it has paid for itself, when it will at
   this pace, whether there is enough for the next one), and every bale before it, side by side. */
import { useForm } from '@inertiajs/react';
import { useState, type FormEvent } from 'react';
import { CheckCircle2, Package, Pencil, Plus, TrendingUp } from 'lucide-react';
import ShopLayout from '../../layouts/ShopLayout';
import { Button, Card, EmptyState, Field, Input, PageHeader, cx } from '../../components/ui';
import { Modal } from '../../components/overlays';
import { useT } from '../../i18n';

type Bale = {
    id: number; label: string; supplier: string | null; note: string | null; opened: string; closed: string | null; isCurrent: boolean;
    pieces: number | null; piecesSold: number; salesCount: number; days: number; paidOff: boolean; percentBack: number | null; daysToPayOff: number | null;
    profitValue: number; perDayValue: number; cost: string; extraCosts: string | null; totalCost: string; takings: string; dailyCosts: string;
    moneyBack: string; profit: string; perDay: string; costPerPiece: string | null;
    input: { label: string; supplier: string; cost: string; extra_costs: string; pieces: string; note: string };
};
type Props = { current: Bale | null; past: Bale[] };

function BaleForm({ bale, onDone }: { bale: Bale | null; onDone: () => void }) {
    // a new bale starts empty: the owner types its own name and costs
    const form = useForm(bale ? bale.input : { label: '', supplier: '', cost: '', extra_costs: '', pieces: '', note: '' });
    const err = form.errors as Record<string, string | undefined>;
    const submit = (e: FormEvent) => {
        e.preventDefault();
        if (bale) form.put(route('bales.update', { bale: bale.id }), { preserveScroll: true, onSuccess: onDone });
        else form.post(route('bales.store'), { preserveScroll: true, onSuccess: onDone });
    };
    return (
        <form onSubmit={submit} className="space-y-4" noValidate>
            <Field label="Name" htmlFor="b-label" error={err.label} required><Input id="b-label" placeholder="e.g. Bale 4: ladies tops" value={form.data.label} onChange={(e) => form.setData('label', e.target.value)} autoFocus /></Field>
            <div className="grid grid-cols-2 gap-3">
                <Field label="What the bale cost" htmlFor="b-cost" error={err.cost_minor} required><Input id="b-cost" inputMode="decimal" value={form.data.cost} onChange={(e) => form.setData('cost', e.target.value)} /></Field>
                <Field label="Transport and other costs" htmlFor="b-extra" error={err.extra_minor} hint="Bringing it to the market"><Input id="b-extra" inputMode="decimal" value={form.data.extra_costs} onChange={(e) => form.setData('extra_costs', e.target.value)} /></Field>
                <Field label={<>Pieces <span className="font-normal text-muted">(roughly, optional)</span></>} htmlFor="b-pieces" error={err.pieces} hint="Shows what each piece cost you"><Input id="b-pieces" inputMode="numeric" value={form.data.pieces} onChange={(e) => form.setData('pieces', e.target.value)} /></Field>
                <Field label={<>Supplier <span className="font-normal text-muted">(optional)</span></>} htmlFor="b-supplier"><Input id="b-supplier" value={form.data.supplier} onChange={(e) => form.setData('supplier', e.target.value)} /></Field>
            </div>
            {!bale && <p className="rounded-xl bg-line-2 p-3 text-xs text-ink-2">The bale on the table now ends today. Clothes left from it simply join the new one: from now on, sales count towards the new bale.</p>}
            <Button type="submit" size="lg" className="w-full" disabled={form.processing}>{bale ? 'Save' : 'Start this bale'}</Button>
        </form>
    );
}

export default function Bales({ current: b, past }: Props) {
    const t = useT();
    const [adding, setAdding] = useState(false);
    const [editing, setEditing] = useState<Bale | null>(null);
    const best = past.length > 1 ? [...past].sort((x, y) => y.perDayValue - x.perDayValue)[0] : null;
    const maxProfit = Math.max(1, ...past.map((p) => Math.abs(p.profitValue)));

    return (
        <ShopLayout title="Bales">
            <PageHeader title={t('Bales')} actions={<Button icon={Plus} onClick={() => setAdding(true)}>Bought a new bale</Button>} />

            {!b ? (
                <EmptyState icon={Package}>No bale yet. When you buy one, press “Bought a new bale”: every sale after that counts towards it.</EmptyState>
            ) : (
                <Card className={b.paidOff ? 'border-emerald-200' : ''}>
                    <div className="flex items-start justify-between gap-3">
                        <div>
                            <p className="text-lg font-extrabold text-ink">{b.label}</p>
                            <p className="text-sm text-muted">Since {b.opened} · day {b.days}{b.supplier ? ` · ${b.supplier}` : ''}</p>
                        </div>
                        <button onClick={() => setEditing(b)} className="grid size-9 place-items-center rounded-lg text-muted hover:bg-line-2" aria-label="Edit"><Pencil className="size-4" /></button>
                    </div>

                    {/* the one number that matters: has it paid for itself yet */}
                    <div className="mt-4">
                        <div className="flex items-baseline justify-between text-sm">
                            <span className="font-semibold text-ink-2">Money back: <b className="text-ink">{b.moneyBack}</b> of {b.totalCost}</span>
                            <span className="font-extrabold text-ink">{b.percentBack ?? 0}%</span>
                        </div>
                        <div className="mt-1.5 h-3 overflow-hidden rounded-full bg-line-2"><div className={cx('h-full rounded-full', b.paidOff ? 'bg-emerald-500' : 'bg-brand')} style={{ width: `${Math.min(100, b.percentBack ?? 0)}%` }} /></div>
                    </div>
                    <div className={cx('mt-3 flex items-start gap-2 rounded-xl p-3 text-sm', b.paidOff ? 'bg-emerald-50 text-emerald-900' : 'bg-amber-50 text-amber-900')}>
                        {b.paidOff ? <CheckCircle2 className="mt-0.5 size-4 shrink-0" aria-hidden /> : <TrendingUp className="mt-0.5 size-4 shrink-0" aria-hidden />}
                        <p>
                            {b.paidOff
                                ? <>This bale has paid for itself. You can buy the next one and still keep <b>{b.profit}</b> profit.</>
                                : b.daysToPayOff
                                    ? <>At {b.perDay} a day it pays for itself in about <b>{b.daysToPayOff} more day{b.daysToPayOff === 1 ? '' : 's'}</b>. After that, everything is profit.</>
                                    : <>Still {b.profit} to go before it pays for itself.</>}
                        </p>
                    </div>

                    <dl className="mt-4 grid grid-cols-2 gap-2 text-sm sm:grid-cols-4">
                        <div className="rounded-xl bg-line-2/60 p-2.5"><dt className="text-xs text-muted">Sold</dt><dd className="font-bold text-ink">{b.takings}</dd><dd className="text-xs text-muted">{b.salesCount} sales{b.piecesSold ? ` · ${b.piecesSold} pieces` : ''}</dd></div>
                        <div className="rounded-xl bg-line-2/60 p-2.5"><dt className="text-xs text-muted">Daily costs</dt><dd className="font-bold text-ink">{b.dailyCosts}</dd><dd className="text-xs text-muted">food, transport, fees</dd></div>
                        <div className="rounded-xl bg-line-2/60 p-2.5"><dt className="text-xs text-muted">The bale</dt><dd className="font-bold text-ink">{b.totalCost}</dd>{b.extraCosts && <dd className="text-xs text-muted">{b.cost} + {b.extraCosts}</dd>}</div>
                        <div className="rounded-xl bg-line-2/60 p-2.5"><dt className="text-xs text-muted">A day</dt><dd className="font-bold text-ink">{b.perDay}</dd><dd className="text-xs text-muted">after daily costs</dd></div>
                    </dl>
                    {b.costPerPiece && (
                        <p className="mt-3 text-sm text-ink-2">Each piece cost you about <b>{b.costPerPiece}</b>{b.pieces ? ` (${b.pieces} pieces)` : ''}. Sell above that.{b.pieces && b.piecesSold ? ` About ${Math.max(0, b.pieces - b.piecesSold)} pieces left.` : ''}</p>
                    )}
                </Card>
            )}

            {past.length > 0 && (
                <>
                    <h2 className="mt-6 mb-2 text-sm font-bold text-muted">Past bales</h2>
                    {best && <p className="mb-2 text-sm text-ink-2">Best so far: <b>{best.label}</b>, {best.perDay} a day.</p>}
                    <ul className="space-y-2">
                        {past.map((p) => (
                            <li key={p.id} className="rounded-card border border-line bg-white p-4 shadow-card">
                                <div className="flex items-start justify-between gap-3">
                                    <div className="min-w-0">
                                        <p className="truncate font-bold text-ink">{p.label}</p>
                                        <p className="text-xs text-muted">{p.opened} → {p.closed} · {p.days} days{p.supplier ? ` · ${p.supplier}` : ''}</p>
                                    </div>
                                    <div className="shrink-0 text-right">
                                        <p className={cx('font-extrabold', p.profitValue >= 0 ? 'text-emerald-700' : 'text-rose-600')}>{p.profitValue >= 0 ? '+' : '−'}{p.profit}</p>
                                        <p className="text-xs text-muted">{p.perDay} a day</p>
                                    </div>
                                </div>
                                <div className="mt-2 h-2 overflow-hidden rounded-full bg-line-2"><div className={cx('h-full rounded-full', p.profitValue >= 0 ? 'bg-emerald-500' : 'bg-rose-400')} style={{ width: `${(Math.abs(p.profitValue) / maxProfit) * 100}%` }} /></div>
                                <p className="mt-2 text-xs text-muted">Sold {p.takings} · daily costs {p.dailyCosts} · bale {p.totalCost}{p.piecesSold ? ` · ${p.piecesSold} pieces` : ''}</p>
                            </li>
                        ))}
                    </ul>
                </>
            )}

            <Modal open={adding} onClose={() => setAdding(false)} title="Bought a new bale">{adding && <BaleForm bale={null} onDone={() => setAdding(false)} />}</Modal>
            <Modal open={!!editing} onClose={() => setEditing(null)} title={editing?.label ?? ''}>{editing && <BaleForm bale={editing} onDone={() => setEditing(null)} />}</Modal>
        </ShopLayout>
    );
}
