/* Customers who pay later: who owes what, most owed first, with how late they are. */
import { Link, router, useForm } from '@inertiajs/react';
import { useEffect, useState, type FormEvent } from 'react';
import { ChevronRight, HandCoins, Plus, Search } from 'lucide-react';
import ShopLayout from '../../layouts/ShopLayout';
import { Badge, Button, EmptyState, Field, Input, PageHeader, Pagination, Textarea, cx } from '../../components/ui';
import { Modal } from '../../components/overlays';
import { useT } from '../../i18n';
import type { Paginated } from '../../types';

type Row = { id: number; name: string; phone: string | null; owed: number; owedLabel: string; overdueDays: number };
type Props = { customers: Paginated<Row>; totals: { owed: string; people: number; overdue: string }; filters: { q: string; show: string } };

function AddCustomer({ onDone }: { onDone: () => void }) {
    const t = useT();
    const form = useForm({ name: '', phone: '', notes: '' });
    const err = form.errors as Record<string, string | undefined>;
    const submit = (e: FormEvent) => { e.preventDefault(); form.post(route('customers.store'), { onSuccess: onDone }); };
    return (
        <form onSubmit={submit} className="space-y-4" noValidate>
            <Field label={t('Name')} htmlFor="c-name" error={err.name} required><Input id="c-name" value={form.data.name} onChange={(e) => form.setData('name', e.target.value)} autoFocus /></Field>
            <Field label={t('Phone number')} htmlFor="c-phone" error={err.phone_e164} hint="For SMS reminders and WhatsApp."><Input id="c-phone" type="tel" inputMode="tel" placeholder="0991 234 567" value={form.data.phone} onChange={(e) => form.setData('phone', e.target.value)} /></Field>
            <Field label={t('Notes')} htmlFor="c-notes"><Textarea id="c-notes" rows={2} value={form.data.notes} onChange={(e) => form.setData('notes', e.target.value)} placeholder="e.g. Works at the market, pays on Fridays" /></Field>
            <Button type="submit" size="lg" className="w-full" disabled={form.processing}>{t('Add customer')}</Button>
        </form>
    );
}

export default function Customers({ customers, totals, filters }: Props) {
    const t = useT();
    const [adding, setAdding] = useState(false);
    const [q, setQ] = useState(filters.q);
    const apply = (patch: Partial<Props['filters']>) => router.get(route('customers.index'), { ...filters, ...patch }, { preserveState: true, preserveScroll: true, replace: true });
    useEffect(() => {
        if (q === filters.q) return;
        const timer = setTimeout(() => apply({ q }), 350);
        return () => clearTimeout(timer);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [q]);

    return (
        <ShopLayout title="Customers">
            <PageHeader title={t('Customers')} actions={<Button icon={Plus} onClick={() => setAdding(true)}>{t('Add customer')}</Button>} />

            <div className="mb-4 grid grid-cols-2 gap-3">
                <div className="rounded-card bg-ink p-4 text-white shadow-card">
                    <p className="text-xs text-white/70">{t('Owed to you')} · {totals.people}</p>
                    <p className="text-2xl font-extrabold tracking-tight">{totals.owed}</p>
                </div>
                <button onClick={() => apply({ show: 'overdue' })} className="rounded-card bg-rose-50 p-4 text-left text-rose-900 shadow-card ring-1 ring-rose-100">
                    <p className="text-xs">{t('Overdue')}</p>
                    <p className="text-2xl font-extrabold tracking-tight">{totals.overdue}</p>
                </button>
            </div>

            <div className="mb-3 flex gap-2">
                <div className="relative flex-1">
                    <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted" aria-hidden />
                    <Input type="search" placeholder={t('Search')} value={q} onChange={(e) => setQ(e.target.value)} className="pl-9" />
                </div>
            </div>
            <div className="no-scrollbar mb-3 flex gap-2 overflow-x-auto">
                {[['owing', t('Who owes')], ['overdue', t('Overdue')], ['all', t('Everyone')]].map(([k, label]) => (
                    <button key={k} onClick={() => apply({ show: k })} className={cx('shrink-0 rounded-full px-4 py-2 text-sm font-bold', filters.show === k ? 'bg-ink text-white' : 'bg-white text-ink-2 ring-1 ring-line')}>{label}</button>
                ))}
            </div>

            {customers.data.length === 0 ? (
                <EmptyState icon={HandCoins}>{filters.show === 'all' ? 'No customers yet. They are added when you sell on credit, or here.' : t('No one owes you anything.')}</EmptyState>
            ) : (
                <ul className="divide-y divide-line overflow-hidden rounded-card border border-line bg-white shadow-card">
                    {customers.data.map((c) => (
                        <li key={c.id}>
                            <Link href={route('customers.show', { customer: c.id })} className="flex items-center gap-3 px-4 py-3 hover:bg-line-2/50">
                                <div className="min-w-0 flex-1">
                                    <p className="truncate text-[15px] font-bold text-ink">{c.name}</p>
                                    <p className="truncate text-xs text-muted">{c.phone ?? 'No phone'}</p>
                                </div>
                                <div className="shrink-0 text-right">
                                    <p className={cx('text-[15px] font-extrabold', c.owed ? 'text-ink' : 'text-muted')}>{c.owed ? c.owedLabel : t('Paid up')}</p>
                                    {c.overdueDays > 0 && <Badge tone="rose">{c.overdueDays} {t('days late')}</Badge>}
                                </div>
                                <ChevronRight className="size-4 shrink-0 text-muted" aria-hidden />
                            </Link>
                        </li>
                    ))}
                </ul>
            )}
            <Pagination page={customers} />
            <Modal open={adding} onClose={() => setAdding(false)} title={t('Add customer')}>{adding && <AddCustomer onDone={() => setAdding(false)} />}</Modal>
        </ShopLayout>
    );
}
