import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { OverviewTab } from "../OverviewTab";
import type { ServiceInstance } from "../../../types";

// Default mock returns an empty list; individual tests override via
// `vi.mocked()` to return widget data.
vi.mock("../../../hooks/useWidgets", () => ({
	useWidgetInstances: vi.fn(() => ({ data: [] })),
}));

vi.mock("../../../components/WidgetInstance", () => ({
	WidgetInstanceCard: ({ widget }: { widget: { title: string } }) => (
		<div data-testid="widget-card">{widget.title}</div>
	),
}));

vi.mock("../../../components/WidgetConfigDialog", () => ({
	WidgetConfigDialog: ({ open }: { open: boolean }) =>
		open ? <div data-testid="config-dialog" /> : null,
}));

const { useWidgetInstances } = await import("../../../hooks/useWidgets");

const instance: ServiceInstance = {
	id: "svc-1",
	service_type: "jellyfin",
	name: "Main Jellyfin",
	config: {},
	secrets_set: {},
	enabled: true,
	created_at: 0,
	updated_at: 0,
};

function mockWidgets(
	widgets: { id: string; title: string; enabled: boolean }[],
) {
	vi.mocked(useWidgetInstances).mockReturnValue({
		data: widgets.map((w, i) => ({
			id: w.id,
			service_id: "svc-1",
			widget_kind: "activity",
			title: w.title,
			config: {},
			enabled: w.enabled,
			sort_order: i,
			created_at: 0,
			updated_at: 0,
		})),
	} as never);
}

describe("OverviewTab", () => {
	it("renders enabled widgets in a grid and hides disabled ones", () => {
		mockWidgets([
			{ id: "w1", title: "Live Sessions", enabled: true },
			{ id: "w2", title: "Disabled Widget", enabled: false },
		]);
		render(<OverviewTab instance={instance} />);
		const cards = screen.getAllByTestId("widget-card");
		expect(cards).toHaveLength(1);
		expect(screen.getByText("Live Sessions")).toBeInTheDocument();
		expect(screen.queryByText("Disabled Widget")).not.toBeInTheDocument();
	});

	it("shows an empty state with an add button when no widgets exist", () => {
		mockWidgets([]);
		render(<OverviewTab instance={instance} />);
		expect(
			screen.getByText(/No widgets on this overview/i),
		).toBeInTheDocument();
		expect(
			screen.getByRole("button", { name: /Add widgets/i }),
		).toBeInTheDocument();
	});

	it("opens the config dialog when Edit widgets is clicked", async () => {
		mockWidgets([{ id: "w1", title: "Live", enabled: true }]);
		render(<OverviewTab instance={instance} />);
		expect(screen.queryByTestId("config-dialog")).not.toBeInTheDocument();
		await userEvent.click(
			screen.getByRole("button", { name: /Edit widgets/i }),
		);
		expect(screen.getByTestId("config-dialog")).toBeInTheDocument();
	});
});
