"use client";

import { clsx } from "clsx";
import { Inventory, Server } from "@/lib/api";
import { formatBytes, relativeAge } from "./format";

/*
 * The four numbers an operator opens a server for, kept above the tabs so they
 * are true on every tab rather than living inside one of them. This is the only
 * part of the page that does not move when the tab changes.
 *
 * A meter is a hairline, not a bar: four of them across the top would otherwise
 * out-shout the hostname, and the number beside each is the value being read —
 * the meter only says how close to full it is.
 */

function Meter({ pct }: { pct: number }) {
    const clamped = Math.max(0, Math.min(100, pct));
    return (
        <div className="mt-2 h-[3px] w-full overflow-hidden rounded-full bg-well">
            <div
                className={clsx("h-full rounded-full transition-[width] duration-500", clamped >= 90 ? "bg-danger" : clamped >= 75 ? "bg-warning" : "bg-accent")}
                style={{ width: `${clamped}%` }}
            />
        </div>
    );
}

function Vital({ label, value, pct, sub }: { label: string; value: string; pct?: number; sub?: string }) {
    return (
        <div className="min-w-0 bg-surface px-4 py-3">
            <div className="flex items-baseline justify-between gap-3">
                <span className="font-mono text-[0.62rem] uppercase tracking-[0.16em] text-text-secondary">{label}</span>
                <span className="font-mono text-sm font-semibold tabular-nums text-text-primary">{value}</span>
            </div>
            {pct !== undefined ? <Meter pct={pct} /> : <div className="mt-2 h-[3px] w-full rounded-full bg-well" />}
            {sub && <p className="mt-1.5 truncate text-xs text-text-tertiary">{sub}</p>}
        </div>
    );
}

/** The partition an operator means by "the disk": the root filesystem, or the
 *  fullest one if there is no root — a Windows agent reports no `/`. */
function primaryPartition(inv: Inventory) {
    const parts = inv.partitions ?? [];
    if (parts.length === 0) return undefined;
    return parts.find((p) => p.mountpoint === "/") ?? parts.reduce((worst, p) => (p.used_bytes / (p.total_bytes || 1) > worst.used_bytes / (worst.total_bytes || 1) ? p : worst));
}

export function VitalsRail({ server, agentUpToDate }: { server: Server; agentUpToDate?: boolean }) {
    const inv = server.inventory;
    const disk = inv ? primaryPartition(inv) : undefined;
    const memPct = inv && inv.memory.total_bytes > 0 ? (inv.memory.used_bytes / inv.memory.total_bytes) * 100 : 0;
    const diskPct = disk && disk.total_bytes > 0 ? (disk.used_bytes / disk.total_bytes) * 100 : 0;

    const agentSub = server.agent_version ? `agent v${server.agent_version}${agentUpToDate === undefined ? "" : agentUpToDate ? " · up to date" : " · update available"}` : "agent version unknown";

    return (
        // One hairline grid rather than four cards: these are readings off one
        // machine, and four bordered panels would read as four subjects.
        <div className="mt-4 grid grid-cols-2 gap-px overflow-hidden rounded border border-border-soft bg-border-soft lg:grid-cols-4">
            {inv ? (
                <>
                    <Vital
                        label="CPU"
                        value={`${inv.cpu.usage_pct.toFixed(0)}%`}
                        pct={inv.cpu.usage_pct}
                        sub={[inv.cpu.cores ? `${inv.cpu.cores} cores` : null, inv.cpu.load1 !== undefined ? `load ${inv.cpu.load1.toFixed(2)}` : null].filter(Boolean).join(" · ") || inv.cpu.model}
                    />
                    <Vital
                        label="Memory"
                        value={`${formatBytes(inv.memory.used_bytes)} / ${formatBytes(inv.memory.total_bytes)}`}
                        pct={memPct}
                        sub={inv.swap_total_bytes > 0 ? `swap ${formatBytes(inv.swap_used_bytes)} / ${formatBytes(inv.swap_total_bytes)}` : "no swap"}
                    />
                    <Vital
                        label={disk ? `Disk ${disk.mountpoint}` : "Disk"}
                        value={disk ? `${diskPct.toFixed(0)}%` : "—"}
                        pct={disk ? diskPct : undefined}
                        sub={disk ? `${formatBytes(disk.used_bytes)} / ${formatBytes(disk.total_bytes)}${disk.fstype ? ` · ${disk.fstype}` : ""}` : "no partitions reported"}
                    />
                </>
            ) : (
                <>
                    <Vital label="CPU" value="—" sub="no metrics reported" />
                    <Vital label="Memory" value="—" sub="no metrics reported" />
                    <Vital label="Disk" value="—" sub="no metrics reported" />
                </>
            )}
            <Vital label="Last seen" value={relativeAge(server.last_seen)} pct={server.status === "active" ? 100 : 0} sub={agentSub} />
        </div>
    );
}
