"use client";

import { useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
import Link from "next/link";
import clsx from "clsx";
import { api, type InjectionState } from "@/lib/api";
import { Ledger } from "@/components/Ledger";
import { IssuePanel } from "./IssuePanel";

const INJECTION: Record<InjectionState, { label: string; tone: string }> = {
    current: { label: "Control plane holds the current licence", tone: "text-valid" },
    stale: {
        label: "Control plane holds an older blob — the reconciler will repair it",
        tone: "text-warn",
    },
    missing: { label: "No matching instance in the control plane", tone: "text-expired" },
    none_issued: { label: "Nothing issued yet, so nothing to inject", tone: "text-ink-3" },
};

export default function StaffInstancePage() {
    const id = String(useParams().id);
    const { data, isLoading } = useQuery({
        queryKey: ["staff-instance", id],
        queryFn: () => api.staff.instance(id),
        refetchInterval: 30_000,
    });

    if (isLoading || !data) return <p className="text-ink-3">Loading…</p>;

    const inj = data.injection.state ? INJECTION[data.injection.state] : undefined;

    return (
        <div className="grid gap-8">
            <header className="grid gap-2">
                <h1 className="text-3xl">{data.instance.name || data.instance.instance_id}</h1>
                <p className="font-mono text-[0.82rem] tabular-nums text-ink-3">
                    {data.instance.instance_id}
                </p>
                <p className="text-[0.82rem]">
                    <Link
                        href={`/staff/accounts/${data.account.account_id}`}
                        className="text-accent underline"
                    >
                        {data.account.name || data.account.account_id}
                    </Link>
                    <span className="text-ink-3">
                        {" "}
                        · {data.instance.deployment} · {data.instance.status}
                        {data.instance.relink_count > 0 &&
                            ` · ${data.instance.relink_count} relinks this term`}
                    </span>
                </p>
                {data.injection.applicable && inj && (
                    <p className={clsx("font-mono text-[0.72rem]", inj.tone)}>{inj.label}</p>
                )}
            </header>

            <section className="grid gap-3 rounded border border-rule bg-panel p-5">
                <h2 className="text-xl">Licence history</h2>
                <Ledger licenses={data.licenses} />
                <IssuePanel
                    instanceId={data.instance.instance_id}
                    deployment={data.instance.deployment}
                />
            </section>
        </div>
    );
}
