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

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

export function QbittorrentSpeedWidget({
	widget,
	refreshIntervalMs,
	description,
}: Props) {
	const { data, isLoading } = useWidgetData(widget.id, refreshIntervalMs);
	const series = data?.data?.series as ChartSeries[] | undefined;
	// Source returns raw bytes/sec; default to bytes/sec + auto scale (MB/s, …).
	const unit = (widget.config.unit as MetricUnit) || "bytes_per_sec";
	const scale = (widget.config.scale as MetricScale) || "auto";

	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>
			) : series && series.length > 0 ? (
				<LineSeriesChart
					series={series}
					unit={unit}
					scale={scale}
					height={220}
					showRangeSelector={false}
				/>
			) : (
				<Alert>
					<AlertDescription>No speed data yet</AlertDescription>
				</Alert>
			)}
		</SectionCard>
	);
}
