import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
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;
}

interface ActiveTorrent {
	name: string | null;
	state: string | null;
	size: number | null;
	progress: number | null;
	dl_speed: number | null;
	up_speed: number | null;
}

function formatSpeed(bytesPerSec: number | null): string {
	if (bytesPerSec === null || bytesPerSec <= 0) return "—";
	const mb = bytesPerSec / 1_000_000;
	if (mb >= 1) return `${mb.toFixed(1)} MB/s`;
	return `${(bytesPerSec / 1000).toFixed(0)} KB/s`;
}

export function QbittorrentActiveTorrentsWidget({
	widget,
	refreshIntervalMs,
	description,
}: Props) {
	const { data, isLoading } = useWidgetData(widget.id, refreshIntervalMs);
	const payload = data?.data as { torrents?: ActiveTorrent[] } | undefined;
	const torrents = payload?.torrents ?? [];

	return (
		<SectionCard title={widget.title} description={description}>
			{isLoading && !data ? (
				<div className="space-y-2">
					<Skeleton className="h-8 w-full" />
					<Skeleton className="h-8 w-full" />
				</div>
			) : data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : torrents.length > 0 ? (
				<ul className="max-h-80 space-y-1.5 overflow-y-auto">
					{torrents.map((t, i) => (
						<li
							key={`${t.name}-${i}`}
							className="flex items-center justify-between gap-2 rounded-md border px-2 py-1 text-sm"
						>
							<span className="truncate">{t.name ?? "Unknown"}</span>
							<div className="flex shrink-0 items-center gap-2">
								<span className="text-xs text-muted-foreground">
									↓{formatSpeed(t.dl_speed)} ↑{formatSpeed(t.up_speed)}
								</span>
								<Badge
									variant={t.state === "downloading" ? "default" : "secondary"}
								>
									{t.state ?? "?"}
								</Badge>
							</div>
						</li>
					))}
				</ul>
			) : (
				<div className="text-xs text-muted-foreground">No active torrents</div>
			)}
		</SectionCard>
	);
}
