import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { MediaTab } from "../MediaTab";
import type { ServiceInstance } from "../../../types";

const instance: ServiceInstance = {
	id: "jellyfin-1",
	service_type: "jellyfin",
	name: "Main Jellyfin",
	config: { base_url: "https://jf.example.com", user_id: "u1" },
	secrets_set: {},
	enabled: true,
	created_at: 1_700_000_000,
	updated_at: 1_700_000_000,
};

vi.mock("../../../hooks/useMedia", () => ({
	useMediaStatus: () => ({
		data: { exists: true, item_count: 42, updated_at_label: "today" },
	}),
	useMediaQuery: () => ({ data: { items: [], total: 0 }, isLoading: false }),
	useBuildIndex: () => ({ mutate: vi.fn(), isPending: false }),
	useStopBuildIndex: () => ({ mutate: vi.fn(), isPending: false }),
	useForceStopBuildIndex: () => ({ mutate: vi.fn(), isPending: false }),
}));

vi.mock("../../../hooks/useDashboard", () => ({
	useCounts: () => ({
		data: { movies: 10, series: 5, episodes: 30 },
	}),
	useLibraries: () => ({ data: [{ id: "lib1" }] }),
}));

vi.mock("../../../hooks/useServices", () => ({
	useServiceInstances: () => ({ data: [] }),
}));

vi.mock("../../../hooks/usePersistentState", () => ({
	usePersistentState: () => [
		{
			search: "",
			types: "Movie,Episode",
			hdrFilter: "All",
			sortKey: "title",
			sortOrder: "Ascending",
			offset: 0,
			pageSize: 100,
			columnVisibility: {},
		},
		vi.fn(),
	],
}));

function renderTab() {
	return render(
		<MemoryRouter>
			<MediaTab instance={instance} />
		</MemoryRouter>,
	);
}

describe("MediaTab", () => {
	it("renders index status and build controls with instance-scoped data", () => {
		renderTab();
		expect(screen.getByText(/42 items/)).toBeInTheDocument();
		expect(
			screen.getByRole("button", { name: /Build index/i }),
		).toBeInTheDocument();
	});

	it("renders library counts", () => {
		renderTab();
		expect(screen.getByText(/10 movies/)).toBeInTheDocument();
		expect(screen.getByText(/5 series/)).toBeInTheDocument();
	});

	it("renders the filter card with search input", () => {
		renderTab();
		expect(screen.getByLabelText("Search")).toBeInTheDocument();
	});
});
