import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { ExternalLink } from "lucide-react";
import { SectionCard } from "../components/SectionCard";
import { useWidgetData } from "../hooks/useWidgets";
import type { WidgetInstance } from "../types";
import { getWidgetDefinition } from "./registry";

interface Props {
	widget: WidgetInstance;
}

export function GrafanaLinkWidget({ widget }: Props) {
	const def = getWidgetDefinition(widget.widget_type);
	const { data, isLoading } = useWidgetData(
		widget.id,
		def?.refreshInterval ?? 0,
	);
	const url = data?.data?.url as string | undefined;

	return (
		<SectionCard title={widget.title} description={def?.description}>
			{isLoading && !data ? (
				<Skeleton className="h-10 w-48" />
			) : data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : url ? (
				<Button asChild>
					<a href={url} target="_blank" rel="noopener noreferrer">
						Open Grafana
						<ExternalLink className="ml-2 h-4 w-4" />
					</a>
				</Button>
			) : (
				<Alert>
					<AlertDescription>No Grafana URL configured.</AlertDescription>
				</Alert>
			)}
		</SectionCard>
	);
}
