"use client";

import { useQuery } from "@tanstack/react-query";
import { API_BASE, NotConnected, api } from "@/lib/api";
import { NotConnectedPanel } from "@/components/NotConnected";
import { formatDate } from "@/lib/format";

export default function BillingPage() {
    const { data, error, isLoading } = useQuery({
        queryKey: ["subscriptions"],
        queryFn: api.subscriptions,
    });

    if (error instanceof NotConnected) return <NotConnectedPanel url={API_BASE} />;
    if (isLoading) return <p className="text-ink-3">Loading…</p>;

    return (
        <div className="grid gap-6">
            <h1 className="text-3xl">Billing</h1>

            {!data || data.length === 0 ? (
                <p className="text-ink-2">
                    You have no subscriptions. Cloud instances and self-hosted licences are both
                    bought from the pricing page.
                </p>
            ) : (
                <div className="overflow-x-auto rounded border border-rule bg-panel">
                    <table className="w-full border-collapse text-left">
                        <thead>
                            <tr className="border-b border-rule bg-panel-2 font-mono text-[0.72rem] uppercase tracking-[0.08em] text-ink-3">
                                <th className="px-4 py-2.5">Plan</th>
                                <th className="px-4 py-2.5">Term</th>
                                <th className="px-4 py-2.5">Status</th>
                                <th className="px-4 py-2.5">Renews</th>
                            </tr>
                        </thead>
                        <tbody>
                            {data.map((s) => (
                                <tr
                                    key={s.subscription_id}
                                    className="border-b border-rule-soft last:border-0"
                                >
                                    <td className="px-4 py-3">{s.tier.replace("_", " ")}</td>
                                    <td className="px-4 py-3">{s.term}</td>
                                    <td className="px-4 py-3">{s.status}</td>
                                    <td className="px-4 py-3 font-mono tabular-nums">
                                        {formatDate(s.current_period_end)}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            )}

            <p className="max-w-xl text-[0.82rem] text-ink-3">
                To change a card, download an invoice or cancel, email support and we will send you
                a billing link. Self-service billing arrives with card payments.
            </p>
        </div>
    );
}
