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 { BackupDashboardSummary } from "../types/backups";
import type { WidgetInstance } from "../types";

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

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

	return (
		<SectionCard title={widget.title} description={description}>
			{isLoading && !data ? (
				<div className="flex flex-row flex-wrap gap-6">
					<Skeleton className="h-10 w-20" />
					<Skeleton className="h-10 w-20" />
					<Skeleton className="h-10 w-20" />
				</div>
			) : data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : summary ? (
				<div className="flex flex-row flex-wrap gap-6">
					<div>
						<div className="text-2xl font-semibold">{summary.total_jobs}</div>
						<div className="text-xs text-muted-foreground">Jobs</div>
					</div>
					<div>
						<div className="text-2xl font-semibold">
							{summary.success_rate_24h}%
						</div>
						<div className="text-xs text-muted-foreground">24h Success</div>
					</div>
					<div>
						<div className="text-2xl font-semibold">
							{summary.active_alerts > 0 ? (
								<Badge variant="destructive">{summary.active_alerts}</Badge>
							) : (
								0
							)}
						</div>
						<div className="text-xs text-muted-foreground">Alerts</div>
					</div>
					{summary.last_failed_at ? (
						<div className="self-center text-xs text-destructive">
							Last failed:{" "}
							{new Date(summary.last_failed_at * 1000).toLocaleString()}
						</div>
					) : null}
				</div>
			) : null}
		</SectionCard>
	);
}
