import { router, usePage } from '@inertiajs/react';
import { Head } from '@inertiajs/react';
import { RefreshCw, Plug, AlertTriangle, CheckCircle2 } from 'lucide-react';

type Provider = {
    key: string; name: string; category: string; is_mocked: boolean;
    connected: boolean; status: string; status_label: string;
    display_name: string | null; sync_frequency: string | null;
    last_synced_at: string | null; next_sync_at: string | null;
    records_imported: number; account_id: number | null;
};

const ATTENTION = ['failed', 'reauthorization_required', 'rate_limited'];
const DOT: Record<string, string> = {
    rentec: 'bg-emerald-500', salesforce: 'bg-sky-500', google_ads: 'bg-amber-500',
    meta_ads: 'bg-blue-600', quickbooks: 'bg-green-600',
};

export default function DataManager() {
    const { providers } = usePage().props as unknown as { providers: Provider[] };

    return (
        <>
            <Head title="Data Manager" />
            <div className="mx-auto w-full max-w-6xl px-6 py-8">
                <header className="mb-8">
                    <h1 className="text-2xl font-semibold tracking-tight text-foreground">Data Manager</h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        Connect your business platforms and monitor synchronization.
                    </p>
                </header>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {providers.map((p) => (
                        <div key={p.key} className="rounded-xl border border-border bg-card p-5 shadow-sm transition hover:shadow-md">
                            <div className="mb-4 flex items-start justify-between">
                                <div className="flex items-center gap-2.5">
                                    <span className={`mt-1 size-2.5 shrink-0 rounded-full ${DOT[p.key] ?? 'bg-muted-foreground'}`} />
                                    <div>
                                        <div className="flex items-center gap-2">
                                            <span className="font-medium text-foreground">{p.name}</span>
                                            {p.is_mocked && (
                                                <span className="rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-amber-700 dark:bg-amber-500/15 dark:text-amber-300">Mock</span>
                                            )}
                                        </div>
                                        <span className="text-xs capitalize text-muted-foreground">{p.category}</span>
                                    </div>
                                </div>
                                <StatusPill status={p.status} label={p.status_label} />
                            </div>

                            {p.connected ? (
                                <dl className="space-y-1.5 text-xs">
                                    <Row label="Account" value={p.display_name ?? '—'} />
                                    <Row label="Frequency" value={p.sync_frequency ?? '—'} />
                                    <Row label="Last sync" value={p.last_synced_at ?? 'never'} />
                                    <Row label="Records" value={p.records_imported.toLocaleString()} />
                                </dl>
                            ) : (
                                <p className="text-xs text-muted-foreground">Not connected yet.</p>
                            )}

                            <div className="mt-5 flex gap-2">
                                {p.connected ? (
                                    <>
                                        <button className="inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium text-foreground transition hover:bg-muted"
                                            onClick={() => router.post(`/data-manager/${p.account_id}/sync`, {}, { preserveScroll: true })}>
                                            <RefreshCw className="size-3.5" /> Sync now
                                        </button>
                                        <button className="rounded-md border border-border px-3 py-1.5 text-xs font-medium text-destructive transition hover:bg-destructive/10"
                                            onClick={() => { if (confirm(`Disconnect ${p.name}?`)) router.delete(`/data-manager/${p.account_id}`, { preserveScroll: true }); }}>
                                            Disconnect
                                        </button>
                                    </>
                                ) : (
                                    <button className="inline-flex items-center gap-1.5 rounded-md bg-primary px-3.5 py-1.5 text-xs font-medium text-primary-foreground transition hover:opacity-90"
                                        onClick={() => router.visit(`/data-manager/connect/${p.key}`)}>
                                        <Plug className="size-3.5" /> Connect
                                    </button>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </>
    );
}

function Row({ label, value }: { label: string; value: string }) {
    return (
        <div className="flex justify-between">
            <dt className="text-muted-foreground">{label}</dt>
            <dd className="font-medium text-foreground">{value}</dd>
        </div>
    );
}

function StatusPill({ status, label }: { status: string; label: string }) {
    const attention = ATTENTION.includes(status);
    const healthy = status === 'healthy';
    const cls = attention ? 'bg-destructive/10 text-destructive'
        : healthy ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300'
        : 'bg-muted text-muted-foreground';
    const Icon = attention ? AlertTriangle : healthy ? CheckCircle2 : null;
    return (
        <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ${cls}`}>
            {Icon && <Icon className="size-3" />}{label}
        </span>
    );
}
