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

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

const widget: WidgetInstance = {
	id: "w1",
	service_id: "s1",
	widget_kind: "chart",
	title: "CPU Usage",
	config: {},
	enabled: true,
	sort_order: 0,
	created_at: 0,
	updated_at: 0,
};

function mockData(data: unknown, error?: string) {
	vi.mocked(useWidgets.useWidgetData).mockReturnValue({
		data: error
			? { widget_id: "w1", error, fetched_at: 0 }
			: { widget_id: "w1", data, fetched_at: 0 },
		isLoading: false,
	} as unknown as ReturnType<typeof useWidgets.useWidgetData>);
}

describe("PrometheusChartWidget", () => {
	it("renders skeleton while loading", () => {
		vi.mocked(useWidgets.useWidgetData).mockReturnValue({
			data: undefined,
			isLoading: true,
		} as unknown as ReturnType<typeof useWidgets.useWidgetData>);
		render(<PrometheusChartWidget widget={widget} refreshIntervalMs={60000} />);
		expect(
			document.querySelector('[data-slot="skeleton"]'),
		).toBeInTheDocument();
	});

	it("renders a chart with series data", () => {
		mockData({
			series: [
				{
					label: "cpu",
					points: [
						{ t: 1000, v: 0.5 },
						{ t: 2000, v: 0.8 },
					],
				},
			],
		});
		render(<PrometheusChartWidget widget={widget} refreshIntervalMs={60000} />);
		// recharts renders an SVG; the title from SectionCard should be present.
		expect(screen.getByText("CPU Usage")).toBeInTheDocument();
	});

	it("shows error Alert on error", () => {
		mockData(null, "promql is required");
		render(<PrometheusChartWidget widget={widget} refreshIntervalMs={60000} />);
		expect(screen.getByText(/promql is required/i)).toBeInTheDocument();
	});

	it("shows empty state when no series", () => {
		mockData({ series: [] });
		render(<PrometheusChartWidget widget={widget} refreshIntervalMs={60000} />);
		expect(screen.getByText(/No data/i)).toBeInTheDocument();
	});
});
