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

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

const statWidget: WidgetInstance = {
	id: "w1",
	service_id: "s1",
	widget_kind: "stat",
	title: "My stat widget",
	config: { stat: "pending" },
	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("RequestStatWidget", () => {
	it("renders the selected stat value + label", () => {
		mockData({ key: "pending", label: "Pending", value: 3 });
		render(<RequestStatWidget widget={statWidget} refreshIntervalMs={30_000} />);
		expect(screen.getByText("3")).toBeInTheDocument();
		expect(screen.getByText("Pending")).toBeInTheDocument();
	});

	it("surfaces an error from the source", () => {
		mockData(null, "Jellyseerr is not configured");
		render(<RequestStatWidget widget={statWidget} refreshIntervalMs={30_000} />);
		expect(screen.getByText(/not configured/i)).toBeInTheDocument();
	});
});

describe("RequestsOverviewWidget", () => {
	it("renders the stats grid + a recent request", () => {
		mockData({
			stats: [
				{ key: "pending", label: "Pending", value: 2 },
				{ key: "total", label: "Total", value: 5 },
			],
			recent: [{ id: 1, name: "Inception", status: "pending" }],
		});
		const overviewWidget: WidgetInstance = {
			...statWidget,
			widget_kind: "stats_overview",
			title: "Overview",
		};
		render(<RequestsOverviewWidget widget={overviewWidget} refreshIntervalMs={30_000} />);
		expect(screen.getByText("Pending")).toBeInTheDocument();
		expect(screen.getByText("Total")).toBeInTheDocument();
		expect(screen.getByText("Inception")).toBeInTheDocument();
	});
});
