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 { AuthentikGroup } from "../api/authentik";
import type { WidgetInstance } from "../types";

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

export function AuthentikGroupsWidget({
	widget,
	refreshIntervalMs,
	description,
}: Props) {
	const { data, isLoading } = useWidgetData(widget.id, refreshIntervalMs);
	const payload = data?.data as { items?: AuthentikGroup[] } | undefined;
	const groups = payload?.items ?? [];
	return (
		<SectionCard title={widget.title} description={description}>
			{isLoading && !data ? (
				<Skeleton className="h-16 w-full" />
			) : data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : groups.length ? (
				<ul className="space-y-1">
					{groups.map((group) => (
						<li key={group.id} className="rounded-md border px-2 py-1 text-sm">
							{group.name}
						</li>
					))}
				</ul>
			) : (
				<p className="text-sm text-muted-foreground">No groups found.</p>
			)}
		</SectionCard>
	);
}
