import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { MetricCard } from "../components/MetricCard";
import { SectionCard } from "../components/SectionCard";
import { useWidgetData } from "../hooks/useWidgets";
import type { WidgetInstance } from "../types";
import type { JellyseerRecentRequest, JellyseerStat } from "../api/jellyseerr";

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

interface OverviewData {
	stats?: JellyseerStat[];
	recent?: JellyseerRecentRequest[];
}

/** All Jellyseerr request stats as a grid, plus a recent-requests list. */
export function RequestsOverviewWidget({
	widget,
	refreshIntervalMs,
	description,
}: Props) {
	const { data, isLoading } = useWidgetData(widget.id, refreshIntervalMs);
	const overview = data?.data as OverviewData | undefined;

	return (
		<SectionCard title={widget.title} description={description}>
			{isLoading && !data ? (
				<Skeleton className="h-32 w-full" />
			) : data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : overview?.stats && overview.stats.length > 0 ? (
				<div className="flex flex-col gap-3">
					<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
						{overview.stats.map((s) => (
							<MetricCard key={s.key} label={s.label} value={String(s.value)} />
						))}
					</div>
					{overview.recent && overview.recent.length > 0 ? (
						<div className="flex flex-col gap-1">
							<span className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
								Recent
							</span>
							{overview.recent.slice(0, 8).map((r, i) => (
								<div
									key={String(r.id ?? i)}
									className="flex items-center justify-between gap-2 text-sm"
								>
									<span className="truncate">{r.name ?? "—"}</span>
									<div className="flex shrink-0 items-center gap-1">
										{r.media_status ? (
											<Badge variant="outline">{r.media_status}</Badge>
										) : null}
										{r.status ? <Badge variant="secondary">{r.status}</Badge> : null}
									</div>
								</div>
							))}
						</div>
					) : null}
				</div>
			) : (
				<Alert>
					<AlertDescription>No request data.</AlertDescription>
				</Alert>
			)}
		</SectionCard>
	);
}
