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 GrafanaPanelWidget({
	widget,
	refreshIntervalMs,
	description,
}: Props) {
	const { data, isLoading } = useWidgetData(widget.id, refreshIntervalMs);
	const embedUrl = data?.data?.embed_url as string | undefined;

	return (
		<SectionCard title={widget.title} description={description}>
			{isLoading && !data ? (
				<Skeleton className="h-[300px] w-full" />
			) : data?.error ? (
				<Alert variant="destructive">
					<AlertDescription>{data.error}</AlertDescription>
				</Alert>
			) : embedUrl ? (
				<div className="flex flex-col gap-2">
					<iframe
						src={embedUrl}
						title={widget.title}
						className="h-[300px] w-full rounded-lg border border-border"
						loading="lazy"
					/>
					<Button variant="outline" size="sm" asChild>
						<a href={embedUrl} target="_blank" rel="noopener noreferrer">
							Open in Grafana
							<ExternalLink className="ml-2 h-3 w-3" />
						</a>
					</Button>
				</div>
			) : (
				<Alert>
					<AlertDescription>No Grafana panel configured.</AlertDescription>
				</Alert>
			)}
		</SectionCard>
	);
}
