"use client";

import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { Button, Card } from "@/components/ui";
import { vulnerabilities, type ServerPackages } from "@/lib/api";
import { SeverityBadge, SEVERITY_ORDER, StateBadge, relativeTime } from "./SeverityVisuals";

/*
 * One server's findings and package inventory.
 *
 * The three states this must keep apart, because they look identical if you are
 * careless and only one of them is good news:
 *
 *   - the agent has never reported          → "no inventory yet"
 *   - the distribution has no advisory feed → "unsupported"
 *   - scanned, nothing found                → "no known vulnerabilities"
 */

function hasReported(p: ServerPackages | { reported: false } | undefined): p is ServerPackages {
    return !!p && !("reported" in p);
}

export function ServerVulnerabilities({ serverId }: { serverId: string }) {
    const findings = useQuery({
        queryKey: ["vulnerabilities", "server", serverId],
        queryFn: () => vulnerabilities.forServer(serverId),
    });

    const packages = useQuery({
        queryKey: ["packages", serverId],
        queryFn: () => vulnerabilities.packagesForServer(serverId),
    });

    const pkg = hasReported(packages.data) ? packages.data : undefined;
    const open = (findings.data ?? []).filter((f) => f.state === "open");

    const counts = SEVERITY_ORDER.map((s) => ({ severity: s, n: open.filter((f) => f.severity === s).length })).filter((c) => c.n > 0);

    return (
        <Card padding={false}>
            <div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-6 py-4">
                <h2 className="text-lg font-semibold text-text-primary">Vulnerabilities</h2>
                <Link href="/vulnerabilities">
                    <Button variant="ghost" size="sm">
                        View All
                    </Button>
                </Link>
            </div>

            <div className="px-6 py-5">
                {packages.isLoading || findings.isLoading ? (
                    <p className="text-sm text-text-secondary">Loading…</p>
                ) : !pkg ? (
                    <p className="text-sm text-text-secondary">No package inventory yet. Agents report hourly, and only when vulnerability scanning is included in this instance&apos;s licence.</p>
                ) : pkg.status === "unsupported" ? (
                    <>
                        <p className="text-sm text-warning">
                            {pkg.os.family} {pkg.os.version_id} has no advisory feed, so this server cannot be scanned.
                        </p>
                        <p className="mt-1 text-xs text-text-tertiary">This is not the same as having no vulnerabilities — it means we cannot answer the question for this distribution.</p>
                    </>
                ) : (
                    <>
                        <div className="flex flex-wrap items-center gap-4">
                            {counts.length === 0 ? (
                                <p className="text-sm text-success">No known vulnerabilities.</p>
                            ) : (
                                counts.map((c) => (
                                    <span key={c.severity} className="flex items-center gap-2">
                                        <SeverityBadge severity={c.severity} />
                                        <span className="font-mono text-lg font-semibold tabular-nums text-text-primary">{c.n}</span>
                                    </span>
                                ))
                            )}
                        </div>

                        <p className="mt-4 font-mono text-[10px] uppercase tracking-[0.16em] text-text-tertiary">
                            {pkg.packages.length} packages · {pkg.os.family} {pkg.os.version_id} · collected {relativeTime(pkg.collected_at)}
                            {pkg.scan_pending && " · rescan queued"}
                        </p>

                        {open.length > 0 && (
                            <ul className="mt-4 space-y-2">
                                {open.slice(0, 10).map((f) => (
                                    <li key={f.id} className="flex flex-wrap items-center gap-3 border-b border-border-soft pb-2 last:border-b-0">
                                        <SeverityBadge severity={f.severity} />
                                        <span className="font-mono text-sm text-text-primary">{f.cve_id}</span>
                                        <span className="font-mono text-xs text-text-secondary">
                                            {f.package_name} {f.installed_version}
                                        </span>
                                        <span className="font-mono text-xs text-text-tertiary">{f.fixed_in ? `→ ${f.fixed_in}` : "no fix published"}</span>
                                        <StateBadge state={f.state} />
                                    </li>
                                ))}
                                {open.length > 10 && <li className="pt-1 text-xs text-text-tertiary">…and {open.length - 10} more on the fleet board.</li>}
                            </ul>
                        )}
                    </>
                )}
            </div>
        </Card>
    );
}
