"use client";

import {
	AlertTriangle,
	CheckCircle2,
	CircleDashed,
	Server,
} from "lucide-react";
import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { authFetch } from "@/lib/auth";
import type { SwarmDashboardRow } from "@/lib/swarm-status";
import { cn } from "@/lib/utils";

interface SwarmsPayload {
	schemaVersion: 1;
	registryPath: string;
	summary: {
		total: number;
		ok: number;
		degraded: number;
		missing: number;
	};
	swarms: SwarmDashboardRow[];
}

function healthIcon(status: SwarmDashboardRow["status"]) {
	if (status === "ok") return <CheckCircle2 className="h-4 w-4 text-success" />;
	if (status === "missing") {
		return <CircleDashed className="h-4 w-4 text-muted-foreground" />;
	}
	return <AlertTriangle className="h-4 w-4 text-warning" />;
}

function statusTone(status: SwarmDashboardRow["status"]) {
	if (status === "ok") return "border-success/40 text-success";
	if (status === "missing") return "border-border text-muted-foreground";
	return "border-warning/40 text-warning";
}

export function SwarmsView() {
	const [payload, setPayload] = useState<SwarmsPayload | null>(null);
	const [error, setError] = useState<string | null>(null);

	useEffect(() => {
		let cancelled = false;
		const load = async () => {
			try {
				const response = await authFetch("/api/swarms");
				if (!response.ok) throw new Error(`HTTP ${response.status}`);
				const data = (await response.json()) as SwarmsPayload;
				if (!cancelled) {
					setPayload(data);
					setError(null);
				}
			} catch (err) {
				if (!cancelled) {
					setError(err instanceof Error ? err.message : String(err));
				}
			}
		};
		void load();
		const timer = window.setInterval(load, 5_000);
		return () => {
			cancelled = true;
			window.clearInterval(timer);
		};
	}, []);

	return (
		<div className="flex h-full flex-col overflow-hidden">
			<div className="border-b border-border px-6 py-3">
				<div className="flex items-center justify-between gap-4">
					<div>
						<h1 className="text-lg font-semibold">Swarms</h1>
						<p className="text-sm text-muted-foreground">
							Per-repo supervised SF status projections
						</p>
					</div>
					<Server className="h-5 w-5 text-muted-foreground" />
				</div>
			</div>
			<div className="flex-1 overflow-y-auto px-6 py-4">
				{error ? (
					<div className="rounded-md border border-destructive/30 p-4 text-sm text-destructive">
						{error}
					</div>
				) : null}
				{payload ? (
					<div className="space-y-4">
						<div className="grid gap-3 md:grid-cols-4">
							<div className="rounded-md border border-border p-3">
								<p className="text-xs text-muted-foreground">Registered</p>
								<p className="mt-1 text-2xl font-semibold">
									{payload.summary.total}
								</p>
							</div>
							<div className="rounded-md border border-border p-3">
								<p className="text-xs text-muted-foreground">Running</p>
								<p className="mt-1 text-2xl font-semibold">
									{payload.summary.ok}
								</p>
							</div>
							<div className="rounded-md border border-border p-3">
								<p className="text-xs text-muted-foreground">Degraded</p>
								<p className="mt-1 text-2xl font-semibold">
									{payload.summary.degraded}
								</p>
							</div>
							<div className="rounded-md border border-border p-3">
								<p className="text-xs text-muted-foreground">Missing</p>
								<p className="mt-1 text-2xl font-semibold">
									{payload.summary.missing}
								</p>
							</div>
						</div>

						{payload.swarms.length === 0 ? (
							<div className="rounded-md border border-border p-6 text-sm text-muted-foreground">
								No repos registered in {payload.registryPath}.
							</div>
						) : (
							<div className="overflow-hidden rounded-md border border-border">
								{payload.swarms.map((swarm) => (
									<div
										key={swarm.id}
										className="border-b border-border p-4 last:border-b-0"
									>
										<div className="flex items-start justify-between gap-4">
											<div className="min-w-0">
												<div className="flex items-center gap-2">
													{healthIcon(swarm.status)}
													<h2 className="truncate text-sm font-semibold">
														{swarm.name}
													</h2>
													<Badge
														variant="outline"
														className={cn(
															"h-5 text-[11px]",
															statusTone(swarm.status),
														)}
													>
														{swarm.status}
													</Badge>
												</div>
												<p className="mt-1 truncate font-mono text-xs text-muted-foreground">
													{swarm.repoPath}
												</p>
											</div>
											<p className="shrink-0 text-xs text-muted-foreground">
												{swarm.updatedAt
													? new Date(swarm.updatedAt).toLocaleTimeString()
													: "no projection"}
											</p>
										</div>
										{swarm.projection ? (
											<div className="mt-3 grid gap-3 text-sm md:grid-cols-4">
												<div>
													<p className="text-xs text-muted-foreground">
														Milestone
													</p>
													<p className="truncate">
														{swarm.projection.state.activeMilestoneId ?? "none"}
													</p>
												</div>
												<div>
													<p className="text-xs text-muted-foreground">
														Current Unit
													</p>
													<p className="truncate">
														{swarm.projection.state.currentUnit ?? "idle"}
													</p>
												</div>
												<div>
													<p className="text-xs text-muted-foreground">Queue</p>
													<p>{swarm.projection.state.queueDepth}</p>
												</div>
												<div>
													<p className="text-xs text-muted-foreground">
														Supervisor
													</p>
													<p className="truncate">
														{swarm.projection.supervisor.kind} /{" "}
														{swarm.projection.supervisor.health}
													</p>
												</div>
											</div>
										) : (
											<p className="mt-3 text-sm text-muted-foreground">
												{swarm.error}
											</p>
										)}
									</div>
								))}
							</div>
						)}
					</div>
				) : (
					<div className="rounded-md border border-border p-6 text-sm text-muted-foreground">
						Loading swarms…
					</div>
				)}
			</div>
		</div>
	);
}
