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

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

export function AuthentikApplicationsWidget({
	widget,
	refreshIntervalMs,
	description,
}: Props) {
	const { data, isLoading } = useWidgetData(widget.id, refreshIntervalMs);
	const payload = data?.data as { items?: AuthentikApplication[] } | undefined;
	const applications = 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>
			) : applications.length ? (
				<ul className="space-y-1">
					{applications.map((application) => (
						<li
							key={application.id || application.slug || application.name}
							className="rounded-md border px-2 py-1 text-sm"
						>
							<span className="font-medium">{application.name}</span>
							{application.slug ? (
								<span className="ml-2 text-xs text-muted-foreground">
									{application.slug}
								</span>
							) : null}
						</li>
					))}
				</ul>
			) : (
				<p className="text-sm text-muted-foreground">No applications found.</p>
			)}
		</SectionCard>
	);
}
