/* SMS loan reminders: the master switch (off by default), when to remind, the message with its placeholders and a
   live preview, usage and cost, and every SMS sent. */
import { useForm } from '@inertiajs/react';
import type { FormEvent } from 'react';
import { MessageSquareText, Save } from 'lucide-react';
import ShopLayout from '../../layouts/ShopLayout';
import { Badge, Button, Card, CardHeader, EmptyState, Field, Input, PageHeader, Pagination, Textarea, Toggle, cx, type Tone } from '../../components/ui';
import PaymentInstructions from '../../components/PaymentInstructions';
import type { Paginated } from '../../types';

type Props = {
    settings: { sms_enabled: boolean; remind_days_before: string; remind_on_due: boolean; remind_overdue_every: string; sms_template: string };
    defaultTemplate: string; placeholders: string[];
    sample: { name: string; business: string; amount: string; due: string };
    costPerMessage: string;
    credits: number;
    topups: { id: number; when: string; credits: number; amount: string | null }[];
    buy: { instructions: string; supportPhone: string; business: string };
    usage: { thisMonth: number; costThisMonth: string; failedThisMonth: number };
    excluded: { id: number; name: string }[];
    log: Paginated<{ id: number; when: string; to: string; customer: string | null; message: string; status: string; error: string | null; type: string; cost: string }>;
};

const TONE: Record<string, Tone> = { sent: 'green', queued: 'amber', failed: 'rose', skipped: 'gray' };

export default function Sms({ settings, defaultTemplate, placeholders, sample, costPerMessage, credits, topups, buy, usage, excluded, log }: Props) {
    const form = useForm(settings);
    const err = form.errors as Record<string, string | undefined>;
    const d = form.data;
    const submit = (e: FormEvent) => { e.preventDefault(); form.put(route('sms.update'), { preserveScroll: true }); };
    const preview = d.sms_template
        .replaceAll('{customer_name}', sample.name).replaceAll('{business_name}', sample.business)
        .replaceAll('{amount}', sample.amount).replaceAll('{due_date}', sample.due).replaceAll('{days_overdue}', '3');
    const parts = preview.length <= 160 ? 1 : Math.ceil(preview.length / 153);

    return (
        <ShopLayout title="SMS reminders">
            <PageHeader title="SMS loan reminders" subtitle="Remind customers automatically, or press “Send reminder now” on a customer at any time." />

            {/* prepaid SMS: how many are left, and how to buy more */}
            <div className={cx('mb-4 rounded-card p-4 shadow-card', credits === 0 ? 'bg-rose-50 text-rose-900 ring-1 ring-rose-200' : credits <= 3 ? 'bg-amber-50 text-amber-900 ring-1 ring-amber-200' : 'bg-ink text-white')}>
                <p className="text-sm opacity-80">SMS left</p>
                <p className="text-4xl font-extrabold tracking-tight">{credits}</p>
                <p className="mt-1 text-sm opacity-80">{credits === 0 ? 'Nothing can be sent until you buy more.' : `Each SMS uses one; a message over 160 characters uses two. About ${costPerMessage} each.`}</p>
            </div>
            <Card className="mb-4">
                <CardHeader title="Buy more SMS" subtitle={`About ${costPerMessage} per SMS. Pay, then send the confirmation: we add them to your account.`} />
                <PaymentInstructions text={buy.instructions} className="mt-3" />
                <a href={`https://wa.me/${buy.supportPhone.replace('+', '')}?text=${encodeURIComponent(`Hello, I would like to buy SMS for ${buy.business}.`)}`} target="_blank" rel="noopener"
                    className="mt-3 inline-flex items-center gap-2 rounded-xl bg-emerald-600 px-4 py-2.5 text-sm font-bold text-white">Ask for more SMS on WhatsApp</a>
                {topups.length > 0 && (
                    <ul className="mt-4 divide-y divide-line border-t border-line text-sm">
                        {topups.map((t) => <li key={t.id} className="flex justify-between py-2"><span className="text-ink-2">{t.when}{t.amount ? ` · ${t.amount}` : ''}</span><span className="font-bold text-ink">+{t.credits} SMS</span></li>)}
                    </ul>
                )}
            </Card>

            <div className="mb-4 grid grid-cols-3 gap-2 text-center">
                <div className="rounded-xl bg-white p-3 ring-1 ring-line"><p className="text-xs text-muted">Sent this month</p><p className="text-xl font-extrabold text-ink">{usage.thisMonth}</p></div>
                <div className="rounded-xl bg-white p-3 ring-1 ring-line"><p className="text-xs text-muted">Cost</p><p className="text-xl font-extrabold text-ink">{usage.costThisMonth}</p></div>
                <div className="rounded-xl bg-white p-3 ring-1 ring-line"><p className="text-xs text-muted">Failed</p><p className={cx('text-xl font-extrabold', usage.failedThisMonth ? 'text-rose-600' : 'text-ink')}>{usage.failedThisMonth}</p></div>
            </div>

            <form onSubmit={submit} noValidate className="space-y-4">
                <Card className={d.sms_enabled ? 'border-emerald-200' : ''}>
                    <div className="flex items-center justify-between gap-3">
                        <div>
                            <p className="text-base font-extrabold text-ink">Automatic reminders {d.sms_enabled ? 'ON' : 'OFF'}</p>
                            <p className="text-sm text-muted">{d.sms_enabled ? 'Customers who owe get a reminder on the days you choose below (9:00 in the morning).' : 'Nothing is sent automatically. You can still send a reminder by hand from a customer’s page.'}</p>
                        </div>
                        <Toggle checked={d.sms_enabled} onChange={(v) => form.setData('sms_enabled', v)} label="SMS reminders" />
                    </div>
                </Card>

                <Card>
                    <CardHeader title="When to remind" />
                    <div className="mt-4 space-y-3">
                        <label className="flex items-center gap-3 text-[15px] text-ink">
                            <Input inputMode="numeric" className="!w-16 text-center" placeholder="–" value={d.remind_days_before} onChange={(e) => form.setData('remind_days_before', e.target.value.replace(/\D/g, ''))} />
                            days before the due date <span className="text-xs text-muted">(empty: no)</span>
                        </label>
                        <div className="flex items-center gap-3 text-[15px] text-ink">
                            <Toggle checked={d.remind_on_due} onChange={(v) => form.setData('remind_on_due', v)} label="On the due date" />On the due date
                        </div>
                        <label className="flex items-center gap-3 text-[15px] text-ink">
                            every <Input inputMode="numeric" className="!w-16 text-center" placeholder="–" value={d.remind_overdue_every} onChange={(e) => form.setData('remind_overdue_every', e.target.value.replace(/\D/g, ''))} />
                            days while overdue <span className="text-xs text-muted">(empty: no)</span>
                        </label>
                        {(err.remind_days_before || err.remind_overdue_every) && <p className="text-sm font-semibold text-rose-600">{err.remind_days_before ?? err.remind_overdue_every}</p>}
                    </div>
                </Card>

                <Card>
                    <CardHeader title="The message" subtitle="These words are filled in for each customer:" />
                    <div className="mt-2 flex flex-wrap gap-1.5">
                        {placeholders.map((p) => <button key={p} type="button" onClick={() => form.setData('sms_template', `${d.sms_template} ${p}`)} className="rounded-md bg-line-2 px-2 py-1 font-mono text-xs text-ink-2 hover:bg-brand/10">{p}</button>)}
                    </div>
                    <Field error={err.sms_template} className="mt-3">
                        <Textarea rows={4} value={d.sms_template} onChange={(e) => form.setData('sms_template', e.target.value)} maxLength={320} />
                    </Field>
                    <div className="mt-3 rounded-xl bg-emerald-50 p-3 text-sm text-emerald-950">
                        <p className="mb-1 text-xs font-bold text-emerald-700">Preview · {preview.length} characters · {parts} SMS</p>{preview}
                    </div>
                    {d.sms_template !== defaultTemplate && <button type="button" onClick={() => form.setData('sms_template', defaultTemplate)} className="mt-2 text-xs font-semibold text-brand">Use the standard message</button>}
                </Card>

                <Button type="submit" size="lg" icon={Save} className="w-full sm:w-auto" disabled={form.processing || !form.isDirty}>{form.isDirty ? 'Save' : 'Saved'}</Button>
            </form>

            {excluded.length > 0 && (
                <p className="mt-4 text-sm text-muted">Never texted (switched off on their page): {excluded.map((c) => c.name).join(', ')}.</p>
            )}

            <h2 className="mt-6 mb-2 text-sm font-bold text-muted">Every SMS sent</h2>
            {log.data.length === 0 ? <EmptyState icon={MessageSquareText}>No SMS yet.</EmptyState> : (
                <ul className="divide-y divide-line overflow-hidden rounded-card border border-line bg-white shadow-card">
                    {log.data.map((m) => (
                        <li key={m.id} className="px-4 py-3">
                            <div className="flex items-center justify-between gap-2">
                                <p className="truncate text-sm font-bold text-ink">{m.customer ?? m.to} <span className="font-normal text-muted">· {m.when}{m.type === 'manual' ? ' · sent by hand' : ''}</span></p>
                                <Badge tone={TONE[m.status] ?? 'gray'}>{m.status === 'skipped' ? 'not sent' : m.status}</Badge>
                            </div>
                            <p className="mt-1 text-sm text-ink-2">{m.message}</p>
                            {m.error && <p className="mt-0.5 text-xs text-rose-700">{m.error}</p>}
                            <p className="mt-0.5 text-xs text-muted">{m.cost}</p>
                        </li>
                    ))}
                </ul>
            )}
            <Pagination page={log} />
        </ShopLayout>
    );
}
