"use client";

import { useQueries, useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { api, Monitor, Rollup } from "@/lib/api";
import { Button } from "@/components/ui";
import {
    DisplayStatus,
    StatusChip,
    Tape,
    avgLatency,
    buildSlots,
    displayStatus,
    formatMs,
    formatPct,
    relativeTime,
    statusStripe,
    targetSummary,
    uptimePct,
} from "@/components/monitors/MonitorVisuals";

/*
 * The list is a stack of channel strips rather than a table. Each row carries
 * 48 hours of history, so "is this healthy" is answered by the shape of the
 * tape and not by one status cell that was true when the page rendered.
 *
 * Uptime is per monitor, so the rollups are fetched per monitor. A fleet is
 * tens of checks, not thousands, and the alternative is a list endpoint that
 * embeds history for every row whether or not anyone looks at it.
 */

const ROW = "grid grid-cols-1 gap-3 sm:grid-cols-[minmax(0,1.15fr)_minmax(0,2fr)_170px] sm:gap-5";

function FleetMeter({ counts, uptime }: { counts: Record<DisplayStatus, number>; uptime: number | null }) {
    const total = counts.up + counts.down + counts.pending + counts.paused;
    const order: DisplayStatus[] = ["up", "pending", "down", "paused"];

    return (
        <div className="rounded-lg border border-border bg-surface p-4 sm:px-5">
            <div className="mb-3 flex flex-wrap items-baseline gap-x-6 gap-y-2">
                <div>
                    <p className="font-mono text-[10px] uppercase tracking-[0.16em] text-text-tertiary">Fleet uptime, last 24 hours</p>
                    <p className="mt-0.5 font-mono text-3xl font-semibold tabular-nums tracking-tight text-text-primary">
                        {formatPct(uptime)}
                        {uptime !== null && <span className="text-base text-text-tertiary">%</span>}
                    </p>
                </div>
                <div className="flex flex-wrap gap-4 sm:ml-auto">
                    {order.map((s) => (
                        <span key={s} className="flex items-center gap-2 text-xs text-text-secondary">
                            <span className={`block h-2.5 w-2.5 rounded-sm ${statusStripe[s]}`} />
                            <span className="font-mono tabular-nums text-text-primary">{counts[s]}</span>
                            {s === "pending" ? "pending" : s}
                        </span>
                    ))}
                </div>
            </div>
            <div
                className="flex h-2 gap-0.5 overflow-hidden rounded-sm bg-well"
                role="img"
                aria-label={`${counts.up} up, ${counts.pending} pending, ${counts.down} down, ${counts.paused} paused of ${total} monitors`}
            >
                {order.map((s) =>
                    counts[s] > 0 ? <span key={s} className={statusStripe[s]} style={{ flex: counts[s] }} /> : null,
                )}
            </div>
        </div>
    );
}

function MonitorRow({ monitor, rollups }: { monitor: Monitor; rollups: Rollup[] }) {
    const status = displayStatus(monitor);
    const slots = buildSlots(rollups);
    const pct = uptimePct(rollups.slice(-24));
    const latency = monitor.state.latency_ms > 0 ? monitor.state.latency_ms : avgLatency(rollups.slice(-1));

    return (
        <Link
            href={`/monitors/${monitor.monitor_id}`}
            className={`${ROW} relative items-center border-t border-border-soft px-4 py-3.5 transition-colors first:border-t-0 hover:bg-surface-2 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent sm:px-5`}
        >
            <span className={`absolute inset-y-0 left-0 w-0.5 ${statusStripe[status]}`} aria-hidden />

            <div className="min-w-0">
                <span className="flex items-center gap-2">
                    <span className="truncate text-sm font-semibold text-text-primary">{monitor.name}</span>
                    <span className="shrink-0 rounded-sm border border-border px-1.5 font-mono text-[10px] uppercase tracking-[0.1em] text-text-secondary">
                        {monitor.type}
                    </span>
                </span>
                <span className="mt-1 block truncate font-mono text-[11.5px] text-text-tertiary">{targetSummary(monitor)}</span>
            </div>

            <Tape slots={slots} live={monitor.enabled} />

            <div className="flex items-baseline gap-3 sm:block sm:text-right">
                <p className={`font-mono text-lg font-semibold tabular-nums ${status === "down" ? "text-danger" : "text-text-primary"}`}>
                    {formatPct(pct)}
                    {pct !== null && <span className="text-xs text-text-tertiary">%</span>}
                </p>
                <p className="font-mono text-[11px] text-text-tertiary sm:mt-1">
                    <StatusChip status={status} className="mr-1.5 align-middle" />
                    {status === "paused" ? "no checks" : `${formatMs(latency)} · ${relativeTime(monitor.state.last_check_at)}`}
                </p>
            </div>
        </Link>
    );
}

export default function MonitorsPage() {
    const { data: monitors, isLoading } = useQuery({
        queryKey: ["monitors"],
        queryFn: () => api.listMonitors(),
        refetchInterval: 30_000,
    });

    const uptimeQueries = useQueries({
        queries: (monitors ?? []).map((m) => ({
            queryKey: ["monitors", m.monitor_id, "uptime"],
            queryFn: () => api.getMonitorUptime(m.monitor_id),
            refetchInterval: 60_000,
        })),
    });

    const counts: Record<DisplayStatus, number> = { up: 0, down: 0, pending: 0, paused: 0 };
    for (const m of monitors ?? []) counts[displayStatus(m)] += 1;

    const fleetRollups = uptimeQueries.flatMap((q) => (q.data ?? []).slice(-24));
    const fleetUptime = uptimePct(fleetRollups);

    return (
        <div className="p-4 sm:p-6 lg:p-8">
            <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
                <div>
                    <p className="font-mono text-[10px] uppercase tracking-[0.16em] text-text-tertiary">
                        Fleet · {monitors?.length ?? 0} {monitors?.length === 1 ? "check" : "checks"}
                    </p>
                    <h1 className="mt-1 text-2xl font-bold tracking-tight text-text-primary">Monitors</h1>
                </div>
                <div className="flex gap-2">
                    <Link href="/settings/notifications">
                        <Button variant="secondary">Notification channels</Button>
                    </Link>
                    <Link href="/monitors/new">
                        <Button variant="primary">New monitor</Button>
                    </Link>
                </div>
            </div>

            {isLoading ? (
                <div className="flex justify-center py-16">
                    <div className="h-8 w-8 animate-spin rounded-full border-2 border-border border-t-accent" />
                </div>
            ) : !monitors || monitors.length === 0 ? (
                <div className="rounded-lg border border-border bg-surface px-6 py-14 text-center">
                    <p className="text-[15px] font-semibold text-text-primary">Nothing is being watched yet.</p>
                    <p className="mx-auto mt-2 max-w-[46ch] text-sm text-text-secondary">
                        Add a check and Vantage records uptime and response time on your interval, opens an incident when it fails, and tells the
                        channels you pick.
                    </p>
                    <Link href="/monitors/new">
                        <Button variant="primary" className="mt-4">
                            Add your first check
                        </Button>
                    </Link>
                </div>
            ) : (
                <>
                    <FleetMeter counts={counts} uptime={fleetUptime} />

                    <div className={`${ROW} hidden px-5 pb-2 pt-5 sm:grid`}>
                        <p className="font-mono text-[10px] uppercase tracking-[0.16em] text-text-tertiary">Monitor</p>
                        <div className="flex items-end justify-between font-mono text-[10px] tracking-[0.08em] text-text-tertiary">
                            <span>48h ago</span>
                            <span>24h</span>
                            <span>now</span>
                        </div>
                        <p className="text-right font-mono text-[10px] uppercase tracking-[0.16em] text-text-tertiary">Uptime 24h · response</p>
                    </div>

                    <div className="overflow-hidden rounded-lg border border-border bg-surface">
                        {monitors.map((m, i) => (
                            <MonitorRow key={m.monitor_id} monitor={m} rollups={uptimeQueries[i]?.data ?? []} />
                        ))}
                    </div>
                </>
            )}
        </div>
    );
}
