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";
import {
	RadialBarChart,
	RadialBar,
	ResponsiveContainer,
	PolarAngleAxis,
} from "recharts";

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

interface GaugeData {
	value: number;
	warn_at?: number | null;
	crit_at?: number | null;
	min?: number | null;
	max?: number | null;
	unit?: string | null;
}

function formatValue(value: number, unit?: string | null): string {
	let formatted: string;
	if (Math.abs(value) >= 100) {
		formatted = value.toFixed(0);
	} else if (Math.abs(value) >= 1) {
		formatted = value.toFixed(2).replace(/\.?0+$/, "");
	} else {
		formatted = value.toFixed(4).replace(/\.?0+$/, "");
	}
	return unit ? `${formatted} ${unit}` : formatted;
}

export function PrometheusGaugeWidget({
	widget,
	refreshIntervalMs,
	description,
}: Props) {
	const { data, isLoading } = useWidgetData(widget.id, refreshIntervalMs);
	const gauge = data?.data as GaugeData | undefined;

	// Compute gauge domain and threshold bands.
	const value = gauge?.value ?? 0;
	const min = gauge?.min ?? 0;
	const max =
		gauge?.max ?? Math.max(value, gauge?.warn_at ?? 0, gauge?.crit_at ?? 0, 1);
	const warnAt = gauge?.warn_at;
	const critAt = gauge?.crit_at;
	const hasBands = warnAt != null && critAt != null;

	// recharts RadialBarChart uses a 0–100 domain for the angle axis.
	// Map our [min, max] domain to [0, 100].
	const range = max - min || 1;
	const toPercent = (v: number) => Math.round(((v - min) / range) * 100);
	const valuePct = Math.max(0, Math.min(100, toPercent(value)));

	// Build track cells: green / amber / red when bands are set, else neutral.
	const trackCells = hasBands
		? [
				{ pct: toPercent(warnAt!), fill: "hsl(var(--chart-1))" }, // green
				{ pct: toPercent(critAt!), fill: "hsl(var(--chart-4))" }, // amber
				{ pct: 100, fill: "hsl(var(--destructive))" }, // red
			]
		: [{ pct: 100, fill: "hsl(var(--muted))" }];

	const valueColor = hasBands
		? value >= critAt!
			? "hsl(var(--destructive))"
			: value >= warnAt!
				? "hsl(var(--chart-4))"
				: "hsl(var(--chart-1))"
		: "hsl(var(--primary))";

	return (
		<SectionCard title={widget.title} description={description}>
			{isLoading && !data ? (
				<Skeleton className="h-[220px] w-full" />
			) : data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : gauge ? (
				<div className="flex flex-col items-center">
					<ResponsiveContainer width="100%" height={200}>
						<RadialBarChart
							innerRadius="65%"
							outerRadius="100%"
							data={[
								...trackCells.map((c) => ({
									name: "track",
									pct: c.pct,
									fill: c.fill,
								})),
								{ name: "value", pct: valuePct, fill: valueColor },
							]}
							startAngle={90}
							endAngle={-270}
						>
							<PolarAngleAxis
								type="number"
								domain={[0, 100]}
								angleAxisId={0}
								tick={false}
							/>
							<RadialBar
								background={{ fill: "hsl(var(--muted))" }}
								dataKey="pct"
								cornerRadius={6}
							/>
						</RadialBarChart>
					</ResponsiveContainer>
					<div className="-mt-12 flex flex-col items-center">
						<span className="text-2xl font-bold" style={{ color: valueColor }}>
							{formatValue(value, gauge.unit)}
						</span>
						{hasBands ? (
							<span className="text-xs text-muted-foreground">
								warn {formatValue(warnAt!, gauge.unit)} · crit{" "}
								{formatValue(critAt!, gauge.unit)}
							</span>
						) : null}
					</div>
				</div>
			) : (
				<Alert>
					<AlertDescription>No data. Check your PromQL query.</AlertDescription>
				</Alert>
			)}
		</SectionCard>
	);
}
