import React, { useEffect, useMemo, useState } from 'react';

type AdminBillingBootstrap = {
    overviewEndpoint: string;
    csrfToken: string;
};

type BillingInvoiceRow = {
    id: string;
    invoiceNumber: string;
    workspaceName: string;
    planName: string;
    billingCycle: string;
    status: string;
    amount: number;
    amountLabel: string;
    currencyCode: string;
    paidAt: string | null;
    paidAtLabel: string | null;
    dueAt: string | null;
    dueAtLabel: string | null;
    provider: string | null;
    createdAt: string | null;
};

type BillingOverviewData = {
    filters: { status: string };
    summary: {
        totalInvoices: number;
        paidInvoices: number;
        pendingInvoices: number;
        collectedThisMonth: number;
        collectedThisYear: number;
        collectedThisMonthLabel: string;
        collectedThisYearLabel: string;
        statusCounts: Record<string, number>;
    };
    charts: {
        paymentGrowth: Array<{ monthKey: string; label: string; total: number }>;
        workspaceGrowth: Array<{ monthKey: string; label: string; total: number }>;
    };
    invoices: BillingInvoiceRow[];
};

const STATUS_OPTIONS = ['all', 'draft', 'initiated', 'pending_payment', 'paid', 'failed', 'cancelled'] as const;

function MiniBarChart({
    title,
    rows,
    money,
}: {
    title: string;
    rows: Array<{ label: string; total: number }>;
    money?: boolean;
}) {
    const max = useMemo(() => Math.max(...rows.map((row) => row.total), 1), [rows]);

    return (
        <div className="rounded-2xl border border-slate-200 bg-white p-4">
            <p className="text-sm font-semibold text-slate-900">{title}</p>
            <div className="mt-4 space-y-2">
                {rows.map((row) => (
                    <div key={row.label} className="grid grid-cols-[90px_1fr_auto] items-center gap-2">
                        <span className="text-xs text-slate-500">{row.label}</span>
                        <div className="h-2 rounded-full bg-slate-100">
                            <div
                                className="h-2 rounded-full bg-emerald-500"
                                style={{ width: `${Math.max(4, (row.total / max) * 100)}%` }}
                            />
                        </div>
                        <span className="text-xs font-semibold text-slate-700">
                            {money ? `$${row.total.toFixed(0)}` : row.total}
                        </span>
                    </div>
                ))}
            </div>
        </div>
    );
}

export function AdminBillingWorkspace({ bootstrap }: { bootstrap: AdminBillingBootstrap }) {
    const [statusFilter, setStatusFilter] = useState<string>('all');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [overview, setOverview] = useState<BillingOverviewData | null>(null);

    useEffect(() => {
        void loadOverview();
    }, [statusFilter, bootstrap.overviewEndpoint]);

    async function loadOverview() {
        setLoading(true);
        setError(null);
        try {
            const query = new URLSearchParams({ status: statusFilter });
            const response = await fetch(`${bootstrap.overviewEndpoint}?${query.toString()}`, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json' },
            });
            const json = await response.json();
            if (!response.ok) {
                throw new Error(json.message ?? 'Could not load billing analytics.');
            }
            setOverview(json.data as BillingOverviewData);
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Could not load billing analytics.');
        } finally {
            setLoading(false);
        }
    }

    return (
        <div className="space-y-6">
            <section className="rounded-[30px] border border-slate-200/80 bg-white p-8 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <p className="text-sm font-semibold uppercase tracking-[0.2em] text-emerald-600">Super admin billing</p>
                <h2 className="mt-2 text-3xl font-semibold tracking-tight text-slate-950">Subscription invoices and growth analytics</h2>
                <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">
                    Track all workspace subscription invoices, filter by invoice status, monitor collections for this month and this year, and see monthly growth for payments and workspaces.
                </p>
            </section>

            <section className="rounded-[30px] border border-slate-200/80 bg-white p-6 shadow-[0_20px_80px_-40px_rgba(15,23,42,0.35)]">
                <div className="flex flex-wrap items-center justify-between gap-3">
                    <label className="flex items-center gap-2 text-sm text-slate-700">
                        <span className="font-semibold">Invoice status:</span>
                        <select
                            value={statusFilter}
                            onChange={(event) => setStatusFilter(event.target.value)}
                            className="rounded-xl border border-slate-300 px-3 py-2 text-sm"
                        >
                            {STATUS_OPTIONS.map((status) => (
                                <option key={status} value={status}>
                                    {status}
                                </option>
                            ))}
                        </select>
                    </label>
                    <button
                        type="button"
                        onClick={loadOverview}
                        className="rounded-xl border border-slate-300 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
                    >
                        Refresh
                    </button>
                </div>

                {error ? (
                    <div className="mt-4 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{error}</div>
                ) : null}

                {loading || !overview ? (
                    <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-600">
                        Loading billing analytics...
                    </div>
                ) : (
                    <>
                        <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                                <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Total invoices</p>
                                <p className="mt-2 text-2xl font-semibold text-slate-950">{overview.summary.totalInvoices}</p>
                            </div>
                            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                                <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Collected this month</p>
                                <p className="mt-2 text-2xl font-semibold text-slate-950">{overview.summary.collectedThisMonthLabel}</p>
                            </div>
                            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                                <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Collected this year</p>
                                <p className="mt-2 text-2xl font-semibold text-slate-950">{overview.summary.collectedThisYearLabel}</p>
                            </div>
                            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                                <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Pending invoices</p>
                                <p className="mt-2 text-2xl font-semibold text-slate-950">{overview.summary.pendingInvoices}</p>
                            </div>
                        </div>

                        <div className="mt-4 grid gap-4 xl:grid-cols-2">
                            <MiniBarChart title="Payments growth (last 12 months)" rows={overview.charts.paymentGrowth} money />
                            <MiniBarChart title="Workspace growth (last 12 months)" rows={overview.charts.workspaceGrowth} />
                        </div>

                        <div className="mt-5 rounded-2xl border border-slate-200 bg-white">
                            <div className="overflow-x-auto">
                                <table className="min-w-full text-left text-sm">
                                    <thead className="bg-slate-50 text-xs uppercase tracking-[0.12em] text-slate-500">
                                        <tr>
                                            <th className="px-4 py-3">Invoice</th>
                                            <th className="px-4 py-3">Workspace</th>
                                            <th className="px-4 py-3">Plan</th>
                                            <th className="px-4 py-3">Amount</th>
                                            <th className="px-4 py-3">Status</th>
                                            <th className="px-4 py-3">Due</th>
                                            <th className="px-4 py-3">Paid</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {overview.invoices.map((invoice) => (
                                            <tr key={invoice.id} className="border-t border-slate-100">
                                                <td className="px-4 py-3 font-semibold text-slate-900">{invoice.invoiceNumber}</td>
                                                <td className="px-4 py-3 text-slate-700">{invoice.workspaceName}</td>
                                                <td className="px-4 py-3 text-slate-700">{invoice.planName}</td>
                                                <td className="px-4 py-3 text-slate-700">{invoice.amountLabel}</td>
                                                <td className="px-4 py-3">
                                                    <span className="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-semibold text-slate-700">
                                                        {invoice.status}
                                                    </span>
                                                </td>
                                                <td className="px-4 py-3 text-slate-700">{invoice.dueAtLabel ?? '-'}</td>
                                                <td className="px-4 py-3 text-slate-700">{invoice.paidAtLabel ?? '-'}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </>
                )}
            </section>
        </div>
    );
}

export type { AdminBillingBootstrap };
