import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { GrafanaPanelWidget } from "../GrafanaPanelWidget";
import type { WidgetInstance } from "../../types";

vi.mock("../../hooks/useWidgets", () => ({
	useWidgetData: vi.fn(),
}));

const widget: WidgetInstance = {
	id: "w2",
	service_id: "s2",
	widget_kind: "panel",
	title: "CPU Usage",
	config: {},
	enabled: true,
	sort_order: 0,
	created_at: 0,
	updated_at: 0,
};

describe("GrafanaPanelWidget", () => {
	it("renders an iframe with the embed URL", async () => {
		const { useWidgetData } = await import("../../hooks/useWidgets");
		vi.mocked(useWidgetData).mockReturnValue({
			data: {
				widget_id: "w2",
				data: {
					embed_url:
						"http://grafana:3000/d-solo/ov/manage?panelId=4&from=now-1h&to=now&kiosk=tv",
				},
				fetched_at: 0,
			},
			isLoading: false,
		} as never);

		const { container } = render(
			<GrafanaPanelWidget widget={widget} refreshIntervalMs={0} />,
		);
		const iframe = container.querySelector("iframe");
		expect(iframe).not.toBeNull();
		expect(iframe?.getAttribute("src")).toContain("d-solo/ov/manage");
		expect(iframe?.getAttribute("src")).toContain("panelId=4");
	});

	it("renders Open in Grafana fallback link", async () => {
		const { useWidgetData } = await import("../../hooks/useWidgets");
		vi.mocked(useWidgetData).mockReturnValue({
			data: {
				widget_id: "w2",
				data: {
					embed_url:
						"http://grafana:3000/d-solo/ov/manage?panelId=4&from=now-1h&to=now&kiosk=tv",
				},
				fetched_at: 0,
			},
			isLoading: false,
		} as never);

		render(<GrafanaPanelWidget widget={widget} refreshIntervalMs={0} />);
		expect(screen.getByText("Open in Grafana")).toBeInTheDocument();
	});

	it("renders error state", async () => {
		const { useWidgetData } = await import("../../hooks/useWidgets");
		vi.mocked(useWidgetData).mockReturnValue({
			data: {
				widget_id: "w2",
				error: "dashboard_uid is required",
				fetched_at: 0,
			},
			isLoading: false,
		} as never);

		render(<GrafanaPanelWidget widget={widget} refreshIntervalMs={0} />);
		expect(screen.getByText("dashboard_uid is required")).toBeInTheDocument();
	});
});
