import { Alert, AlertDescription } from "@/components/ui/alert";
import { Skeleton } from "@/components/ui/skeleton";
import { SectionCard } from "../components/SectionCard";
import { useWidgetData } from "../hooks/useWidgets";
import type { WidgetInstance } from "../types";

interface Props {
	widget: WidgetInstance;
	refreshIntervalMs: number;
	description?: string;
}

type SeriesPoint = {
	t: number;
	v: number | null;
};

type Series = {
	label: string;
	points: SeriesPoint[];
};

function formatMetricResult(series: Series[] | undefined): string {
	if (!series || series.length === 0) return "No data";
	if (series.length === 1) {
		const last = [...series[0].points].reverse().find((p) => p.v !== null);
		return last ? String(last.v) : "No data";
	}
	return series
		.map((s) => {
			const last = [...s.points].reverse().find((p) => p.v !== null);
			return `${s.label}: ${last ? last.v : "n/a"}`;
		})
		.join("\n");
}

export function PrometheusMetricWidget({
	widget,
	refreshIntervalMs,
	description,
}: Props) {
	const { data, isLoading } = useWidgetData(widget.id, refreshIntervalMs);
	const series = data?.data?.result as Series[] | undefined;

	return (
		<SectionCard title={widget.title} description={description}>
			{isLoading && !data ? (
				<Skeleton className="h-10 w-32" />
			) : data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : (
				<pre className="whitespace-pre-wrap text-sm">
					{formatMetricResult(series)}
				</pre>
			)}
		</SectionCard>
	);
}
