"use client";

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

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

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

    const rows = subs.data ?? [];

    // Each subscription names the instance it pays for, because tier and term
    // are per-licence rather than per-account. Resolving the name here is the
    // difference between "professional · annual" and knowing which install that is.
    const nameFor = (instanceId?: string) => account.data?.instances.find((i) => i.instance_id === instanceId)?.name;

    return (
        <div className="grid gap-6">
            <PageHeader
                title="Billing"
                subtitle="One subscription per instance each carries its own tier and term."
                record={account.data ? [{ key: "Billing", value: account.data.account.billing_email }] : undefined}
            />

            <PageFrame
                aside={
                    <>
                        <RailCard title="Account">
                            <RailFacts
                                rows={[
                                    {
                                        label: "Billing contact",
                                        value: account.data?.account.billing_email ?? "—",
                                    },
                                    { label: "Status", value: account.data?.account.status ?? "—" },
                                    { label: "Subscriptions", value: rows.length },
                                ]}
                            />
                        </RailCard>
                        <RailCard title="Need a change?">
                            <p className="text-[0.82rem] text-ink-2">Change a card, download an invoice or cancel from the billing portal. It covers every subscription on this account.</p>
                            <ManageBillingButton />
                            <p className="text-[0.82rem] text-ink-2">Anything else, email support.</p>
                            <a href="mailto:support@hostxtra.co.uk" className="text-[0.82rem] font-semibold text-accent underline">
                                support@hostxtra.co.uk
                            </a>
                        </RailCard>
                    </>
                }
            >
                {rows.length === 0 ? (
                    <p className="rounded border border-rule bg-panel p-5 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.68rem] uppercase tracking-[0.1em] text-ink-3">
                                    <th className="px-4 py-2.5 font-normal">Instance</th>
                                    <th className="px-4 py-2.5 font-normal">Plan</th>
                                    <th className="px-4 py-2.5 font-normal">Term</th>
                                    <th className="px-4 py-2.5 font-normal">Status</th>
                                    <th className="px-4 py-2.5 font-normal">Renews</th>
                                </tr>
                            </thead>
                            <tbody>
                                {rows.map((s) => (
                                    <tr key={s.subscription_id} className="border-b border-rule-soft last:border-0">
                                        <td className="px-4 py-3">{nameFor(s.instance_id) ?? <span className="text-ink-3">Not linked yet</span>}</td>
                                        <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>
                )}
            </PageFrame>
        </div>
    );
}
