/* One supply, bottle by bottle: how long each lasted, how many services it served, and (owner) what those services
   brought in against what the bottle cost, so you can see whether it paid off and what it costs per service. */
import { router, usePage } from '@inertiajs/react';
import { Droplets, Sparkles } from 'lucide-react';
import ShopLayout from '../../layouts/ShopLayout';
import { Badge, Button, Card, CardHeader, EmptyState, PageHeader, cx } from '../../components/ui';
import { qty } from '../../lib';
import type { Product, SharedProps } from '../../types';

type Batch = {
    id: number; isOpen: boolean; opened: string; finished: string | null; days: number; uses: number; openedBy: string | null; unit: string;
    byService: { name: string; count: number; revenue?: string }[];
    cost?: string; revenue?: string; costPerUse?: string | null; times?: number | null;
};
type SupplyDetail = Product & {
    usedBy: { id: number; name: string; priceLabel: string }[]; avgUses: number | null; avgDays: number | null;
    usesLeft?: number | null; costPerUse?: string | null; open?: { id: number } | null;
};

export default function Supply({ supply: s, batches }: { supply: SupplyDetail; batches: Batch[] }) {
    const { auth } = usePage<SharedProps>().props;
    const owner = auth?.role === 'owner';
    const unit = s.unit || 'bottle';

    return (
        <ShopLayout title={s.name}>
            <PageHeader title={s.name} subtitle={`${qty(Math.max(0, s.stock ?? 0))} unopened ${unit}${s.stock === 1 ? '' : 's'}`} back={{ href: route('products.index', { kind: 'supply' }), label: 'Supplies' }}
                actions={<Button icon={Sparkles} onClick={() => router.post(route('supplies.open', { product: s.id }), {}, { preserveScroll: true })}>Open a new {unit}</Button>} />

            <div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
                <Card><p className="text-xs text-muted">One {unit} lasts</p><p className="text-xl font-extrabold text-ink">{s.avgUses != null ? `${s.avgUses} services` : '–'}</p></Card>
                <Card><p className="text-xs text-muted">About</p><p className="text-xl font-extrabold text-ink">{s.avgDays != null ? `${s.avgDays} days` : '–'}</p></Card>
                {owner && <Card><p className="text-xs text-muted">Costs per service</p><p className="text-xl font-extrabold text-ink">{s.costPerUse ?? '–'}</p></Card>}
                <Card><p className="text-xs text-muted">Left in the open {unit}</p><p className="text-xl font-extrabold text-ink">{s.usesLeft != null ? `≈ ${s.usesLeft}` : '–'}</p></Card>
            </div>
            {s.avgUses == null && <p className="mb-4 rounded-xl bg-sky-50 p-3 text-sm text-sky-900">These fill in when the first {unit} is finished: press “{unit[0].toUpperCase() + unit.slice(1)} finished” when it runs out.</p>}
            {s.usedBy.length > 0 && <p className="mb-4 text-sm text-muted">Used by: {s.usedBy.map((u) => u.name).join(', ')}.</p>}

            {batches.length === 0 ? <EmptyState icon={Droplets}>No {unit}s opened yet.</EmptyState> : (
                <div className="space-y-3">
                    {batches.map((b) => (
                        <Card key={b.id} className={b.isOpen ? 'border-brand/30' : ''}>
                            <CardHeader title={<span className="flex flex-wrap items-center gap-2">{b.opened}{b.finished ? ` → ${b.finished}` : ''} {b.isOpen && <Badge tone="brand">Open now</Badge>}</span>}
                                subtitle={`${b.days} day${b.days === 1 ? '' : 's'} · ${qty(b.uses)} service${b.uses === 1 ? '' : 's'}${b.openedBy ? ` · ${b.openedBy}` : ''}`} />
                            {owner && (
                                <div className="mt-3 grid grid-cols-3 gap-2 text-sm">
                                    <div className="rounded-xl bg-line-2/60 p-2.5"><p className="text-xs text-muted">The {b.unit} cost</p><p className="font-bold text-ink">{b.cost}</p></div>
                                    <div className={cx('rounded-xl p-2.5', b.times != null && b.times >= 1 ? 'bg-emerald-50 text-emerald-900' : 'bg-line-2/60')}>
                                        <p className="text-xs opacity-75">Services brought in</p><p className="font-bold">{b.revenue}</p>
                                    </div>
                                    <div className="rounded-xl bg-line-2/60 p-2.5"><p className="text-xs text-muted">Per service</p><p className="font-bold text-ink">{b.costPerUse ?? '–'}</p></div>
                                </div>
                            )}
                            {owner && b.times != null && b.uses > 0 && <p className="mt-2 text-xs text-muted">The services paid for the {b.unit} {b.times}× over (they also used your time and other supplies).</p>}
                            {b.byService.length > 0 && (
                                <ul className="mt-3 space-y-1 text-sm">
                                    {b.byService.map((x) => <li key={x.name} className="flex justify-between"><span className="text-ink-2">{x.name} × {qty(x.count)}</span>{x.revenue && <span className="font-semibold text-ink">{x.revenue}</span>}</li>)}
                                </ul>
                            )}
                            {b.isOpen && <Button size="sm" variant="secondary" className="mt-3" onClick={() => router.post(route('batches.finish', { batch: b.id }), {}, { preserveScroll: true })}>{unit[0].toUpperCase() + unit.slice(1)} finished</Button>}
                        </Card>
                    ))}
                </div>
            )}
        </ShopLayout>
    );
}
