import { Head, router, usePage } from '@inertiajs/react';
import { useState } from 'react';
import { Database, Plug, RefreshCw, CircleCheck, CircleX, AlertTriangle, Plus } from 'lucide-react';
import { RentecConnectModal } from '@/components/data-manager/RentecConnectModal';

type Account = {
    id: number; display_name: string; status: string; frequency: string;
    last_synced_human: string; records: number; entities: string[];
};
type Provider = {
    key: string; name: string; category: string; auth_type: string;
    supports_multiple: boolean; accounts: Account[];
};

const DOT: Record<string, string> = {
    property: 'bg-emerald-500', crm: 'bg-blue-500', advertising: 'bg-amber-500',
    accounting: 'bg-emerald-500', analytics: 'bg-slate-500',
};

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

    const connect = (p: Provider) => {
        // Rentec authenticates with a stored key, so it takes a form rather than a redirect.
        if (p.key === 'rentec') { setRentecModal(true); return; }
        window.location.href = `/data-manager/connect/${p.key}`;
    };

    const rentecCount = providers.find((p) => p.key === 'rentec')?.accounts.length ?? 0;

    return (
        <>
            <Head title="Data Manager" />
            <div className="mx-auto w-full max-w-5xl px-6 py-8">
                <header className="mb-6">
                    <h1 className="flex items-center gap-2 text-2xl font-semibold tracking-tight text-foreground">
                        <Database className="size-5 text-primary" /> 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) => (
                        <section key={p.key} className="rounded-xl border border-border bg-card p-5">
                            <div className="mb-3 flex items-start justify-between">
                                <div className="flex items-start gap-2">
                                    <span className={`mt-1.5 size-2 rounded-full ${DOT[p.category] ?? 'bg-slate-400'}`} />
                                    <div>
                                        <p className="font-semibold text-foreground">{p.name}</p>
                                        <p className="text-xs capitalize text-muted-foreground">{p.category}</p>
                                    </div>
                                </div>
                                {p.accounts.length === 0 && (
                                    <span className="rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">Not connected</span>
                                )}
                            </div>

                            {p.accounts.length === 0 ? (
                                <>
                                    <p className="mb-3 text-sm text-muted-foreground">Not connected yet.</p>
                                    <button onClick={() => connect(p)}
                                        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 hover:opacity-90">
                                        <Plug className="size-3.5" /> Connect
                                    </button>
                                </>
                            ) : (
                                <div className="space-y-3">
                                    {p.accounts.map((a) => (
                                        <div key={a.id} className="rounded-lg border border-border p-3">
                                            <div className="mb-2 flex items-center justify-between">
                                                <p className="text-sm font-medium text-foreground">{a.display_name}</p>
                                                <StatusBadge status={a.status} />
                                            </div>
                                            <dl className="mb-2 space-y-0.5 text-[11px] text-muted-foreground">
                                                <div className="flex justify-between"><dt>Frequency</dt><dd>{a.frequency}</dd></div>
                                                <div className="flex justify-between"><dt>Last sync</dt><dd>{a.last_synced_human}</dd></div>
                                                <div className="flex justify-between"><dt>Records</dt><dd>{a.records.toLocaleString()}</dd></div>
                                            </dl>
                                            <div className="flex gap-2">
                                                <button className="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-[11px] font-medium hover:bg-muted"
                                                    onClick={() => router.post(`/data-manager/${a.id}/sync`, {}, { preserveScroll: true })}>
                                                    <RefreshCw className="size-3" /> Sync now
                                                </button>
                                                <button className="rounded-md border border-border px-2.5 py-1 text-[11px] font-medium text-destructive hover:bg-destructive/10"
                                                    onClick={() => { if (confirm(`Disconnect ${a.display_name}?`)) router.delete(`/data-manager/${a.id}`, { preserveScroll: true }); }}>
                                                    Disconnect
                                                </button>
                                            </div>
                                        </div>
                                    ))}

                                    {p.supports_multiple && (
                                        <button onClick={() => connect(p)}
                                            className="inline-flex w-full items-center justify-center gap-1.5 rounded-md border border-dashed border-border py-1.5 text-xs font-medium text-muted-foreground hover:border-primary/40 hover:text-foreground">
                                            <Plus className="size-3.5" /> Add another {p.name} account
                                        </button>
                                    )}
                                </div>
                            )}
                        </section>
                    ))}
                </div>
            </div>

            {rentecModal && (
                <RentecConnectModal existingCount={rentecCount} onClose={() => setRentecModal(false)} />
            )}
        </>
    );
}

function StatusBadge({ status }: { status: string }) {
    if (status === 'healthy') {
        return <span className="inline-flex items-center gap-1 rounded bg-emerald-100 px-1.5 py-0.5 text-[10px] font-medium text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300">
            <CircleCheck className="size-3" /> Healthy</span>;
    }
    if (status === 'failed') {
        return <span className="inline-flex items-center gap-1 rounded bg-destructive/10 px-1.5 py-0.5 text-[10px] font-medium text-destructive">
            <CircleX className="size-3" /> Failed</span>;
    }
    if (status === 'reauthorization_required') {
        return <span className="inline-flex items-center gap-1 rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:bg-amber-500/15 dark:text-amber-300">
            <AlertTriangle className="size-3" /> Reconnect</span>;
    }
    return <span className="rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">{status}</span>;
}
