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";

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

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

	return (
		<SectionCard title={widget.title} description={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>
	);
}
