/* One business, for the platform admin: who they are, their billing (on/off, fee, trial and paid-up dates, payments,
   suspension) and SMS usage. Activity is shown as counts only: no amounts from their sales. */
import { router, useForm } from '@inertiajs/react';
import { useState, type FormEvent } from 'react';
import { Activity, Ban, CreditCard, MessageCircle, MessageSquareText, Play, Plus, Receipt, Save, Send, Users } from 'lucide-react';
import PlatformLayout from '../../layouts/PlatformLayout';
import { Badge, Button, ButtonLink, Card, CardHeader, DescList, EmptyState, Field, Input, PageHeader, Select, Textarea, Toggle } from '../../components/ui';
import { Modal } from '../../components/overlays';
import { StatusBadge } from '../../components/status';
import type { BillingStatus, Person } from '../../types';

type BusinessDetail = {
    id: number; name: string; type: string; owner: string | null; ownerPhone: string | null; whatsapp: string | null;
    status: BillingStatus; statusLabel: string; fee: string; trialEnds: string | null; paidUntil: string | null; locksOn: string | null;
    users: number | null; joined: string; currency: string; hours: string | null; billingEnabled: boolean; feeInput: string;
    trialEndsInput: string; paidUntilInput: string; suspendedAt: string | null; suspensionReason: string | null; smsEnabled: boolean;
    productCount: number; saleCount: number; lastSale: string | null; lastLogin: string | null;
};
type Props = {
    business: BusinessDetail; users: Person[];
    payments: { id: number; date: string; amount: string; months: number; method: string; reference: string | null; until: string; by: string | null }[];
    sms: { credits: number; topups: { id: number; when: string; credits: number; amount: string | null; by: string | null }[]; thisMonth: number; total: number; costThisMonth: string; failed: number };
    methods: Record<string, string>; currency: string; today: string;
};

function BillingCard({ b, currency }: { b: BusinessDetail; currency: string }) {
    const form = useForm({ billing_enabled: b.billingEnabled, monthly_fee: b.feeInput, trial_ends_at: b.trialEndsInput, paid_until: b.paidUntilInput });
    const err = form.errors as Record<string, string | undefined>;
    const submit = (e: FormEvent) => { e.preventDefault(); form.put(route('platform.businesses.billing', { business: b.id }), { preserveScroll: true }); };
    return (
        <Card>
            <CardHeader icon={CreditCard} title="Billing" subtitle="Turn billing off to let a business use the app free." />
            <form onSubmit={submit} className="mt-4 space-y-4" noValidate>
                <div className="flex items-center justify-between gap-3 rounded-xl border border-line p-3">
                    <div>
                        <p className="text-sm font-bold text-ink">Billing {form.data.billing_enabled ? 'on' : 'off'}</p>
                        <p className="text-xs text-muted">{form.data.billing_enabled ? 'They pay the monthly fee; unpaid accounts lock after the grace days.' : 'Free: never locks for payment.'}</p>
                    </div>
                    <Toggle checked={form.data.billing_enabled} onChange={(v) => form.setData('billing_enabled', v)} label="Billing on" />
                </div>
                <div className="grid gap-3 sm:grid-cols-3">
                    <Field label={`Monthly fee (${currency})`} htmlFor="fee" error={err.fee_minor}>
                        <Input id="fee" inputMode="decimal" value={form.data.monthly_fee} onChange={(e) => form.setData('monthly_fee', e.target.value)} disabled={!form.data.billing_enabled} />
                    </Field>
                    <Field label="Trial until" htmlFor="trial" error={err.trial_ends_at} hint="Extend to give more free days.">
                        <Input id="trial" type="date" value={form.data.trial_ends_at} onChange={(e) => form.setData('trial_ends_at', e.target.value)} disabled={!form.data.billing_enabled} />
                    </Field>
                    <Field label="Paid until" htmlFor="paid" error={err.paid_until} hint="Set by payments; change only to correct.">
                        <Input id="paid" type="date" value={form.data.paid_until} onChange={(e) => form.setData('paid_until', e.target.value)} disabled={!form.data.billing_enabled} />
                    </Field>
                </div>
                <Button type="submit" icon={Save} disabled={form.processing || !form.isDirty}>{form.isDirty ? 'Save billing' : 'Saved'}</Button>
            </form>
        </Card>
    );
}

/** SMS the business bought: added to what they have left. */
function SmsCreditsForm({ b, methods, onDone }: { b: BusinessDetail; methods: Record<string, string>; onDone: () => void }) {
    const form = useForm({ credits: '100', amount: '', method: 'airtel_money', reference: '' });
    const err = form.errors as Record<string, string | undefined>;
    const submit = (e: FormEvent) => { e.preventDefault(); form.post(route('platform.businesses.sms-credits', { business: b.id }), { preserveScroll: true, onSuccess: onDone }); };
    return (
        <form onSubmit={submit} className="space-y-4" noValidate>
            <div className="grid grid-cols-2 gap-3">
                <Field label="SMS to add" htmlFor="sc-credits" error={err.credits}><Input id="sc-credits" inputMode="numeric" value={form.data.credits} onChange={(e) => form.setData('credits', e.target.value)} /></Field>
                <Field label="Amount paid (optional)" htmlFor="sc-amount" error={err.amount_minor}><Input id="sc-amount" inputMode="decimal" value={form.data.amount} onChange={(e) => form.setData('amount', e.target.value)} /></Field>
                <Field label="Method" htmlFor="sc-method">
                    <Select id="sc-method" value={form.data.method} onChange={(e) => form.setData('method', e.target.value)}>
                        {Object.entries(methods).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                    </Select>
                </Field>
                <Field label="Reference" htmlFor="sc-ref"><Input id="sc-ref" value={form.data.reference} onChange={(e) => form.setData('reference', e.target.value)} /></Field>
            </div>
            <Button type="submit" className="w-full" disabled={form.processing}>Add SMS</Button>
        </form>
    );
}

function PaymentForm({ b, methods, today, onDone }: { b: BusinessDetail; methods: Record<string, string>; today: string; onDone: () => void }) {
    const form = useForm({ amount: b.feeInput, months: '1', paid_at: today, method: 'airtel_money', reference: '', note: '' });
    const err = form.errors as Record<string, string | undefined>;
    const fee = Number(b.feeInput) || 0;
    const submit = (e: FormEvent) => { e.preventDefault(); form.post(route('platform.businesses.payments', { business: b.id }), { preserveScroll: true, onSuccess: onDone }); };
    return (
        <form onSubmit={submit} className="space-y-4" noValidate>
            <div className="grid grid-cols-2 gap-3">
                <Field label="Months" htmlFor="pm-months" error={err.months}>
                    <Select id="pm-months" value={form.data.months} onChange={(e) => { form.setData((d) => ({ ...d, months: e.target.value, amount: fee ? String(fee * Number(e.target.value)) : d.amount })); }}>
                        {[1, 2, 3, 6, 12].map((m) => <option key={m} value={String(m)}>{m} month{m === 1 ? '' : 's'}</option>)}
                    </Select>
                </Field>
                <Field label="Amount paid" htmlFor="pm-amount" error={err.amount_minor}><Input id="pm-amount" inputMode="decimal" value={form.data.amount} onChange={(e) => form.setData('amount', e.target.value)} /></Field>
                <Field label="Paid on" htmlFor="pm-date" error={err.paid_at}><Input id="pm-date" type="date" max={today} value={form.data.paid_at} onChange={(e) => form.setData('paid_at', e.target.value)} /></Field>
                <Field label="Method" htmlFor="pm-method" error={err.method}>
                    <Select id="pm-method" value={form.data.method} onChange={(e) => form.setData('method', e.target.value)}>
                        {Object.entries(methods).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                    </Select>
                </Field>
            </div>
            <Field label={<>Reference <span className="font-normal text-muted">(optional)</span></>} htmlFor="pm-ref" error={err.reference}><Input id="pm-ref" placeholder="Transaction ID" value={form.data.reference} onChange={(e) => form.setData('reference', e.target.value)} /></Field>
            <p className="text-xs text-muted">The paid period continues from the current paid-up date (or the trial end, or today if it has lapsed).</p>
            <Button type="submit" className="w-full" disabled={form.processing}>{form.processing ? 'Saving…' : 'Record payment'}</Button>
        </form>
    );
}

export default function BusinessPage({ business: b, users, payments, sms, methods, currency, today }: Props) {
    const [paying, setPaying] = useState(false);
    const [addingSms, setAddingSms] = useState(false);
    const [suspending, setSuspending] = useState(false);
    const [reason, setReason] = useState('');
    const [reasonErr, setReasonErr] = useState<string | undefined>();

    return (
        <PlatformLayout title={b.name}>
            <PageHeader title={b.name} subtitle={`${b.type} · joined ${b.joined}`} back={{ href: route('platform.businesses.index'), label: 'Businesses' }}
                actions={<>
                    {b.whatsapp && <Button variant="secondary" icon={MessageCircle} onClick={() => window.open(b.whatsapp!, '_blank', 'noopener')}>WhatsApp owner</Button>}
                    <Button icon={Plus} onClick={() => setPaying(true)}>Record payment</Button>
                </>} />

            {b.suspendedAt && (
                <div className="mb-4 flex flex-wrap items-center gap-3 rounded-card border border-rose-200 bg-rose-50 p-4 text-sm text-rose-900">
                    <Ban className="size-5 shrink-0" aria-hidden />
                    <p className="flex-1"><span className="font-bold">Suspended {b.suspendedAt}.</span> {b.suspensionReason}</p>
                    <Button size="sm" icon={Play} onClick={() => router.post(route('platform.businesses.reactivate', { business: b.id }), {}, { preserveScroll: true })}>Reactivate</Button>
                </div>
            )}

            <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_340px]">
                <div className="min-w-0 space-y-6">
                    <BillingCard key={`${b.billingEnabled}${b.feeInput}${b.trialEndsInput}${b.paidUntilInput}`} b={b} currency={currency} />
                    <Card>
                        <CardHeader icon={Receipt} title="Payments" />
                        {payments.length ? (
                            <ul className="mt-2 divide-y divide-line">
                                {payments.map((p) => (
                                    <li key={p.id} className="flex flex-wrap items-center justify-between gap-2 py-2.5 text-sm">
                                        <div>
                                            <p className="font-bold text-ink">{p.amount} <span className="font-normal text-muted">· {p.months} month{p.months === 1 ? '' : 's'}</span></p>
                                            <p className="text-xs text-muted">{p.date} · {p.method}{p.reference ? ` · ${p.reference}` : ''}{p.by ? ` · by ${p.by}` : ''}</p>
                                        </div>
                                        <Badge tone="green">to {p.until}</Badge>
                                    </li>
                                ))}
                            </ul>
                        ) : <EmptyState icon={Receipt}>No payments recorded yet.</EmptyState>}
                    </Card>
                    <Card>
                        <CardHeader icon={Users} title="People" />
                        <ul className="mt-2 divide-y divide-line">
                            {users.map((u) => (
                                <li key={u.id} className="flex items-center justify-between gap-3 py-2.5 text-sm">
                                    <div><p className="font-bold text-ink">{u.name}</p><p className="text-xs text-muted">{u.phoneLabel}{u.lastLogin ? ` · last in ${u.lastLogin}` : ''}</p></div>
                                    <Badge tone={u.role === 'owner' ? 'brand' : u.isActive ? 'green' : 'gray'}>{u.isActive ? u.roleLabel : 'Turned off'}</Badge>
                                </li>
                            ))}
                        </ul>
                    </Card>
                </div>

                <aside className="space-y-6">
                    <Card>
                        <CardHeader icon={CreditCard} title="Status" />
                        <div className="mt-3"><StatusBadge status={b.status} label={b.statusLabel} /></div>
                        <DescList className="mt-3" items={[
                            ['Fee', b.billingEnabled ? `${b.fee} / month` : 'Billing off'],
                            ['Trial until', b.trialEnds ?? '–'],
                            ['Paid until', b.paidUntil ?? '–'],
                            ...(b.locksOn ? [['Locks on', b.locksOn] as [string, string]] : []),
                        ]} />
                        {!b.suspendedAt && <Button variant="ghost" size="sm" icon={Ban} className="mt-4 text-rose-700" onClick={() => setSuspending(true)}>Suspend</Button>}
                    </Card>
                    <Card>
                        <CardHeader icon={Activity} title="Activity" subtitle="Counts only. Their takings stay private." />
                        <DescList className="mt-3" items={[
                            ['Products', b.productCount],
                            ['Sales recorded', b.saleCount],
                            ['Last sale', b.lastSale ?? 'None yet'],
                            ['Last sign-in', b.lastLogin ?? '–'],
                            ['Currency', b.currency],
                            ['Hours', b.hours ?? '–'],
                        ]} />
                    </Card>
                    <Card>
                        <CardHeader icon={MessageSquareText} title="SMS" subtitle={b.smsEnabled ? 'Automatic reminders on' : 'Automatic reminders off'} />
                        <div className="mt-3 flex items-end justify-between gap-3">
                            <div><p className="text-xs text-muted">SMS left</p><p className={`text-3xl font-extrabold ${sms.credits === 0 ? 'text-rose-600' : 'text-ink'}`}>{sms.credits}</p></div>
                            <div className="flex gap-2">
                                <ButtonLink size="sm" variant="secondary" icon={Send} href={route('platform.sms', { business: b.id })}>Send SMS</ButtonLink>
                                <Button size="sm" icon={Plus} onClick={() => setAddingSms(true)}>Add SMS</Button>
                            </div>
                        </div>
                        <DescList className="mt-3" items={[
                            ['This month', sms.thisMonth],
                            ['Cost this month', sms.costThisMonth],
                            ['Failed this month', sms.failed],
                            ['All time', sms.total],
                        ]} />
                        {sms.topups.length > 0 && (
                            <ul className="mt-3 divide-y divide-line border-t border-line text-sm">
                                {sms.topups.map((t) => <li key={t.id} className="flex justify-between py-1.5"><span className="text-muted">{t.when}{t.amount ? ` · ${t.amount}` : ''}</span><span className="font-bold text-ink">+{t.credits}</span></li>)}
                            </ul>
                        )}
                    </Card>
                </aside>
            </div>

            <Modal open={addingSms} onClose={() => setAddingSms(false)} title="Add SMS" subtitle={`${b.name} has ${sms.credits} left`}>
                {addingSms && <SmsCreditsForm b={b} methods={methods} onDone={() => setAddingSms(false)} />}
            </Modal>
            <Modal open={paying} onClose={() => setPaying(false)} title="Record a payment" subtitle={b.name}>
                {paying && <PaymentForm b={b} methods={methods} today={today} onDone={() => setPaying(false)} />}
            </Modal>
            <Modal open={suspending} onClose={() => setSuspending(false)} title={`Suspend ${b.name}?`} subtitle="Their team can only reach the Billing page until you reactivate. Nothing is deleted.">
                <Field label="Reason (the owner sees it)" htmlFor="sus-reason" error={reasonErr}>
                    <Textarea id="sus-reason" rows={2} value={reason} onChange={(e) => setReason(e.target.value)} />
                </Field>
                <div className="mt-4 flex justify-end gap-2">
                    <Button variant="ghost" onClick={() => setSuspending(false)}>Cancel</Button>
                    <Button variant="danger" icon={Ban} onClick={() => router.post(route('platform.businesses.suspend', { business: b.id }), { reason }, {
                        preserveScroll: true, onSuccess: () => setSuspending(false), onError: (e) => setReasonErr(e.reason),
                    })}>Suspend</Button>
                </div>
            </Modal>
        </PlatformLayout>
    );
}
