/* A day's sales: the total, how it was paid, and each sale. Staff see their own; the owner sees everyone's and the profit. */
import { Link, router, usePage } from '@inertiajs/react';
import { ChevronLeft, ChevronRight, Receipt } from 'lucide-react';
import ShopLayout from '../../layouts/ShopLayout';
import { Badge, EmptyState, Pagination, cx } from '../../components/ui';
import { useT } from '../../i18n';
import type { Paginated, Sale, SharedProps } from '../../types';

type Props = {
    date: string; dateLabel: string; isToday: boolean;
    sales: Paginated<Sale>;
    totals: { count: number; total: string; byMethod: { label: string; total: string; count: number }[]; profit?: string };
    /** kaunjika: the day's money in and out */
    day: {
        sold: string; spent: string; left: string; leftValue: number;
        cashLeft: string; cashLeftValue: number; pockets: { label: string; value: number; left: string }[];
        byCategory: { label: string; total: string; count: number }[];
        items: { id: number; category: string; amount: string; note: string | null; time: string; by: string | null }[];
    } | null;
};

/** Today on the phone's own clock (not UTC: just after midnight in Malawi, UTC is still yesterday). */
const localToday = () => { const d = new Date(); d.setMinutes(d.getMinutes() - d.getTimezoneOffset()); return d.toISOString().slice(0, 10); };

const shift = (date: string, days: number) => {
    const d = new Date(`${date}T12:00:00`);
    d.setDate(d.getDate() + days);
    return d.toISOString().slice(0, 10);
};

export default function Sales({ date, dateLabel, isToday, sales, totals, day }: Props) {
    const { auth } = usePage<SharedProps>().props;
    const t = useT();
    const go = (d: string) => router.get(route('sales.index'), { date: d }, { preserveScroll: true });

    return (
        <ShopLayout title="Sales">
            <div className="mb-4 flex items-center gap-2">
                <button onClick={() => go(shift(date, -1))} className="grid size-11 place-items-center rounded-xl bg-white ring-1 ring-line" aria-label="Day before"><ChevronLeft className="size-5" /></button>
                <label className="relative flex-1 text-center">
                    <span className="block text-lg font-extrabold text-ink">{dateLabel}</span>
                    <span className="block text-xs text-muted">{auth?.role === 'owner' ? 'All staff' : 'Your sales'} · tap to pick a day</span>
                    <input type="date" value={date} max={localToday()} onChange={(e) => e.target.value && go(e.target.value)} className="absolute inset-0 cursor-pointer opacity-0" aria-label="Pick a day" />
                </label>
                <button onClick={() => go(shift(date, 1))} disabled={isToday} className="grid size-11 place-items-center rounded-xl bg-white ring-1 ring-line disabled:opacity-30" aria-label="Next day"><ChevronRight className="size-5" /></button>
            </div>

            {day ? (
                /* kaunjika: the money in hand after the day's expenses, pocket by pocket */
                <div className="mb-4 rounded-card bg-ink p-4 text-white shadow-card">
                    <p className="text-sm text-white/70">{t('Cash available after expenses')}</p>
                    <p className={cx('text-3xl font-extrabold tracking-tight', day.cashLeftValue < 0 && 'text-rose-300')}>{day.cashLeftValue < 0 ? '−' : ''}{day.cashLeft}</p>
                    <p className="mt-0.5 text-sm text-white/70">{day.sold} {t('made')} − {day.spent} {t('spent')}</p>
                    {day.pockets.length > 1 && (
                        <div className="mt-3 flex flex-wrap gap-2">
                            {day.pockets.map((p) => <span key={p.label} className="rounded-lg bg-white/10 px-2.5 py-1 text-xs font-semibold">{t(p.label)}: {p.value < 0 ? '−' : ''}{p.left}</span>)}
                        </div>
                    )}
                </div>
            ) : (
            <div className="mb-4 rounded-card bg-ink p-4 text-white shadow-card">
                <p className="text-sm text-white/70">{totals.count} sale{totals.count === 1 ? '' : 's'}</p>
                <p className="text-3xl font-extrabold tracking-tight">{totals.total}</p>
                {totals.profit && <p className="mt-0.5 text-sm text-white/70">Profit on goods: <span className="font-bold text-white">{totals.profit}</span></p>}
                {totals.byMethod.length > 0 && (
                    <div className="mt-3 flex flex-wrap gap-2">
                        {totals.byMethod.map((m) => <span key={m.label} className="rounded-lg bg-white/10 px-2.5 py-1 text-xs font-semibold">{m.label}: {m.total}</span>)}
                    </div>
                )}
            </div>
            )}

            {/* kaunjika: money in, money out item by item, and what is left */}
            {day && (
                <div className="mb-4 rounded-card border border-line bg-white p-4 shadow-card">
                    <div className="flex items-baseline justify-between text-[15px]">
                        <span className="font-semibold text-ink-2">{t('Money made')}</span>
                        <span className="font-extrabold text-ink">{day.sold}</span>
                    </div>
                    <p className="mt-3 mb-1 text-sm font-bold text-ink">{t('Expenses')}</p>
                    {day.items.length === 0 ? <p className="text-sm text-muted">{t('Nothing spent.')}</p> : (
                        <>
                            <ul className="divide-y divide-line-2 text-sm">
                                {day.items.map((e) => (
                                    <li key={e.id} className="flex items-baseline justify-between gap-3 py-1.5">
                                        <span className="min-w-0 text-ink-2"><span className="font-semibold text-ink">{t(e.category)}</span>{e.note ? ` · ${e.note}` : ''} <span className="text-xs text-muted">{e.time}</span></span>
                                        <span className="shrink-0 font-semibold text-ink">{e.amount}</span>
                                    </li>
                                ))}
                            </ul>
                            {day.byCategory.length > 1 && (
                                <div className="mt-2 flex flex-wrap gap-1.5">
                                    {day.byCategory.map((c) => <span key={c.label} className="rounded-lg bg-line-2 px-2 py-1 text-xs font-semibold text-ink-2">{t(c.label)}: {c.total}</span>)}
                                </div>
                            )}
                        </>
                    )}
                    <div className="mt-2 flex items-baseline justify-between border-t border-line pt-2 text-[15px]">
                        <span className="font-semibold text-ink-2">{t('Total expenses')}</span>
                        <span className="font-bold text-ink">{day.spent}</span>
                    </div>
                    <div className={cx('mt-2 flex items-baseline justify-between rounded-xl px-3 py-2.5', day.leftValue >= 0 ? 'bg-emerald-50 text-emerald-900' : 'bg-rose-50 text-rose-900')}>
                        <span className="font-bold">{day.leftValue >= 0 ? t('Left after expenses') : t('Spent more than made')}</span>
                        <span className="text-xl font-extrabold">{day.left}</span>
                    </div>
                </div>
            )}

            {sales.data.length === 0 ? (
                <EmptyState icon={Receipt}>No sales {isToday ? 'yet today' : 'on this day'}.</EmptyState>
            ) : (
                <ul className="divide-y divide-line overflow-hidden rounded-card border border-line bg-white shadow-card">
                    {sales.data.map((s) => (
                        <li key={s.id}>
                            <Link href={route('sales.show', { sale: s.id })} className={cx('flex items-center gap-3 px-4 py-3 hover:bg-line-2/50', s.voided && 'opacity-60')}>
                                <div className="w-12 shrink-0 text-sm font-bold text-muted">{s.time}</div>
                                <div className="min-w-0 flex-1">
                                    <p className={cx('truncate text-[15px] font-bold text-ink', s.voided && 'line-through')}>{s.summary}</p>
                                    <p className="truncate text-xs text-muted">#{s.number} · {s.methodLabel}{auth?.role === 'owner' && s.by ? ` · ${s.by}` : ''}</p>
                                </div>
                                <div className="shrink-0 text-right">
                                    <p className={cx('text-[15px] font-extrabold text-ink', s.voided && 'line-through')}>{s.totalLabel}</p>
                                    {s.voided && <Badge tone="rose">Cancelled</Badge>}
                                </div>
                            </Link>
                        </li>
                    ))}
                </ul>
            )}
            <Pagination page={sales} />
        </ShopLayout>
    );
}
