"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { API_BASE, NotConnected, api } from "@/lib/api";
import { NotConnectedPanel } from "@/components/NotConnected";
import { Queue } from "@/components/Queue";
import { PageFrame, RailCard, RailFacts } from "@/components/PageFrame";
import { PageHeader } from "@/components/PageHeader";
import { StatePill } from "@/components/StatePill";
import { LinkButton } from "@/components/Button";
import { daysRemaining, formatStamp } from "@/lib/format";

const HOURS_48 = 48 * 3600_000;

export default function StaffDashboard() {
    const injection = useQuery({ queryKey: ["injection"], queryFn: api.staff.injectionHealth });
    const expiring = useQuery({
        queryKey: ["instances", "expiring"],
        queryFn: () => api.staff.instances({ expiring: "true" }),
    });
    const pastDue = useQuery({
        queryKey: ["subs", "past_due"],
        queryFn: () => api.staff.subscriptions("past_due"),
    });
    const unlinked = useQuery({
        queryKey: ["instances", "awaiting_link"],
        queryFn: () => api.staff.instances({ status: "awaiting_link" }),
    });
    const audit = useQuery({ queryKey: ["staff-audit"], queryFn: () => api.staff.audit() });
    const allInstances = useQuery({
        queryKey: ["instances", "all"],
        queryFn: () => api.staff.instances(),
    });

    if (injection.error instanceof NotConnected) return <NotConnectedPanel url={API_BASE} />;

    const stale = (unlinked.data ?? []).filter((i) => Date.now() - new Date(i.created_at).getTime() > HOURS_48);

    const failed = injection.data?.count ?? 0;
    const instances = allInstances.data ?? [];

    return (
        <div className="grid gap-6">
            <PageHeader
                title="Operations"
                subtitle={failed > 0 ? "Injection failures come first those instances are paying for a licence they have not received." : "Nothing failing. Queues below are routine chasing."}
                actions={
                    <LinkButton variant="line" href="/staff/accounts">
                        Find an account
                    </LinkButton>
                }
                record={[{ key: "Checked", value: formatStamp(new Date().toISOString()) }]}
                status={failed > 0 ? <StatePill state="expired" /> : <StatePill state="valid" />}
            />

            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <Queue
                    title="Failed injections"
                    tone="expired"
                    count={failed}
                    items={(injection.data?.failed ?? []).slice(0, 4).map((i) => ({
                        label: i.name || i.instance_id,
                        href: `/staff/instances/${i.instance_id}`,
                        meta: i.inject_failed_at ? new Date(i.inject_failed_at).toISOString().slice(11, 16) : "",
                    }))}
                />
                <Queue
                    title="Expiring ≤ 14 days"
                    tone="warn"
                    count={expiring.data?.length ?? 0}
                    items={(expiring.data ?? []).slice(0, 4).map((i) => ({
                        label: i.name || i.instance_id,
                        href: `/staff/instances/${i.instance_id}`,
                        meta: i.tier ?? "",
                    }))}
                />
                <Queue
                    title="Past due"
                    tone="expired"
                    count={pastDue.data?.length ?? 0}
                    items={(pastDue.data ?? []).slice(0, 4).map((s) => ({
                        label: s.instance_id || s.account_id,
                        href: `/staff/accounts/${s.account_id}`,
                        meta: `${daysRemaining(s.current_period_end)}d`,
                    }))}
                />
                <Queue
                    title="Unlinked > 48h"
                    tone="accent"
                    count={stale.length}
                    items={stale.slice(0, 4).map((i) => ({
                        label: i.name || i.instance_id,
                        href: `/staff/accounts/${i.account_id}`,
                        meta: `${Math.floor((Date.now() - new Date(i.created_at).getTime()) / 86_400_000)}d`,
                    }))}
                />
            </div>

            <PageFrame
                aside={
                    <RailCard title="Fleet">
                        <RailFacts
                            rows={[
                                { label: "Instances", value: instances.length },
                                {
                                    label: "Cloud",
                                    value: instances.filter((i) => i.deployment === "cloud").length,
                                },
                                {
                                    label: "Self-hosted",
                                    value: instances.filter((i) => i.deployment === "self_hosted").length,
                                },
                                {
                                    label: "Awaiting link",
                                    value: (unlinked.data ?? []).length,
                                },
                            ]}
                        />
                        <Link href="/staff/licenses" className="text-[0.82rem] font-semibold text-accent underline">
                            All licences
                        </Link>
                    </RailCard>
                }
            >
                <section className="overflow-hidden rounded border border-rule bg-panel">
                    <header className="flex flex-wrap items-center justify-between gap-3 border-b border-rule-soft bg-panel-2 px-4 py-3">
                        <div>
                            <h2 className="text-[0.95rem]">Recent activity</h2>
                            <p className="text-[0.8rem] text-ink-2">Every licence issued, relinked or reaped, newest first.</p>
                        </div>
                        <Link href="/staff/audit" className="text-[0.82rem] font-semibold text-accent underline">
                            Full audit
                        </Link>
                    </header>
                    <div className="overflow-x-auto">
                        <table className="w-full border-collapse text-left text-[0.86rem]">
                            <thead>
                                <tr className="border-b border-rule-soft font-mono text-[0.64rem] uppercase tracking-[0.11em] text-ink-3">
                                    <th className="px-4 py-2 font-normal">Time</th>
                                    <th className="px-4 py-2 font-normal">Action</th>
                                    <th className="px-4 py-2 font-normal">Target</th>
                                    <th className="px-4 py-2 font-normal">Actor</th>
                                </tr>
                            </thead>
                            <tbody>
                                {(audit.data ?? []).slice(0, 12).map((e, n) => (
                                    <tr key={n} className="border-b border-rule-soft last:border-0">
                                        <td className="px-4 py-2.5 font-mono tabular-nums text-ink-2">{new Date(e.created_at).toISOString().slice(11, 16)}</td>
                                        <td className="px-4 py-2.5">{e.action}</td>
                                        <td className="px-4 py-2.5 text-ink-2">{e.target ?? "—"}</td>
                                        <td className="px-4 py-2.5 text-ink-3">{e.actor}</td>
                                    </tr>
                                ))}
                                {audit.data?.length === 0 && (
                                    <tr>
                                        <td colSpan={4} className="px-4 py-6 text-ink-3">
                                            Nothing yet today.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </section>
            </PageFrame>
        </div>
    );
}
