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

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

const widget: WidgetInstance = {
	id: "wm1",
	service_id: "s1",
	widget_kind: "mean",
	title: "Avg CPU",
	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: "wm1", error, fetched_at: 0 }
			: { widget_id: "wm1", data, fetched_at: 0 },
		isLoading: false,
	} as unknown as ReturnType<typeof useWidgets.useWidgetData>);
}

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

	it("renders the mean value with unit", () => {
		mockData({ value: 23.5, unit: "%" });
		render(<PrometheusMeanWidget widget={widget} refreshIntervalMs={60000} />);
		expect(screen.getByText("Avg CPU")).toBeInTheDocument();
		expect(screen.getByText(/23.5 %/)).toBeInTheDocument();
	});

	it("renders the mean value without unit", () => {
		mockData({ value: 1500, unit: null });
		render(<PrometheusMeanWidget widget={widget} refreshIntervalMs={60000} />);
		expect(screen.getByText(/1500/)).toBeInTheDocument();
	});

	it("shows error Alert on error", () => {
		mockData(null, "Mean requires a single-series query");
		render(<PrometheusMeanWidget widget={widget} refreshIntervalMs={60000} />);
		expect(screen.getByText(/single-series/i)).toBeInTheDocument();
	});

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