/* One sale: what was sold, how it was paid, who sold it. The owner can cancel it (stock goes back; it's logged). */
import { Link, router } from '@inertiajs/react';
import { useState } from 'react';
import { Ban } from 'lucide-react';
import ShopLayout from '../../layouts/ShopLayout';
import { Badge, Button, Card, Field, PageHeader, Textarea } from '../../components/ui';
import { Modal } from '../../components/overlays';
import type { Sale } from '../../types';

export default function SalePage({ sale, canVoid }: { sale: Sale; canVoid: boolean }) {
    const [voiding, setVoiding] = useState(false);
    const [reason, setReason] = useState('');
    const [error, setError] = useState<string | undefined>();
    const [busy, setBusy] = useState(false);
    const submit = () => router.post(route('sales.void', { sale: sale.id }), { reason }, {
        preserveScroll: true, onStart: () => setBusy(true), onFinish: () => setBusy(false),
        onSuccess: () => setVoiding(false), onError: (e) => setError(e.reason),
    });

    return (
        <ShopLayout title={`Sale #${sale.number}`}>
            <PageHeader title={`Sale #${sale.number}`} subtitle={`${sale.soldAt}${sale.by ? ` · ${sale.by}` : ''}`} back={{ href: route('sales.index'), label: 'Sales' }} />

            {sale.voided && (
                <div className="mb-4 rounded-card border border-rose-200 bg-rose-50 p-4 text-sm text-rose-900">
                    <p className="font-bold">Cancelled {sale.voidedAt}{sale.voidedBy ? ` by ${sale.voidedBy}` : ''}</p>
                    {sale.voidReason && <p className="mt-0.5">“{sale.voidReason}”</p>}
                </div>
            )}

            <Card>
                {sale.kind === 'quick' ? (
                    <p className="text-[15px] text-ink-2">{sale.note || 'Quick sale'}</p>
                ) : (
                    <ul className="divide-y divide-line">
                        {sale.items?.map((i, n) => (
                            <li key={n} className="flex items-start justify-between gap-3 py-2.5">
                                <div>
                                    <p className="text-[15px] font-bold text-ink">{i.name}</p>
                                    <p className="text-xs text-muted">{i.quantityLabel} × {i.unitPriceLabel}</p>
                                </div>
                                <p className="text-[15px] font-bold text-ink">{i.lineTotalLabel}</p>
                            </li>
                        ))}
                    </ul>
                )}
                <div className="mt-3 flex items-baseline justify-between border-t border-line pt-3">
                    <span className="text-sm font-semibold text-muted">Total</span>
                    <span className="text-2xl font-extrabold text-ink">{sale.totalLabel}</span>
                </div>
                <div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
                    <Badge tone="brand">{sale.methodLabel}</Badge>
                    {sale.enteredLate && <Badge tone="amber">Entered after the shift</Badge>}
                    {sale.customer && <Link href={route('customers.show', { customer: sale.customer.id })} className="font-semibold text-brand">{sale.customer.name}</Link>}
                    {sale.profitLabel && <span className="text-muted">Profit: <span className="font-bold text-ink">{sale.profitLabel}</span></span>}
                </div>
                {sale.kind === 'items' && sale.note && <p className="mt-3 text-sm text-muted">Note: {sale.note}</p>}
            </Card>

            {canVoid && <Button variant="secondary" icon={Ban} className="mt-4 w-full sm:w-auto" onClick={() => setVoiding(true)}>Cancel this sale</Button>}

            <Modal open={voiding} onClose={() => setVoiding(false)} title={`Cancel sale #${sale.number}?`} subtitle="It stops counting in totals and the stock goes back. The activity log keeps a record.">
                <Field label="Why?" htmlFor="reason" error={error} required>
                    <Textarea id="reason" rows={2} value={reason} onChange={(e) => setReason(e.target.value)} placeholder="e.g. Customer returned the goods" />
                </Field>
                <div className="mt-4 flex justify-end gap-2">
                    <Button variant="ghost" onClick={() => setVoiding(false)}>Keep it</Button>
                    <Button variant="danger" icon={Ban} onClick={submit} disabled={busy}>{busy ? 'Cancelling…' : 'Cancel sale'}</Button>
                </div>
            </Modal>
        </ShopLayout>
    );
}
