import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { adminApi } from "../lib/api";
import { AnalyticsStudioPage } from "./AnalyticsStudioPage";

vi.mock("../lib/api", () => ({
  adminApi: {
    get: vi.fn(),
  },
}));

describe("AnalyticsStudioPage", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("loads curated datasets and switches charts", async () => {
    vi.mocked(adminApi.get).mockImplementation(async (path: string) => {
      if (path === "/admin/datasets") {
        return {
          data: {
            datasets: [
              {
                description: "New users over time.",
                id: "profile_growth",
                label: "User Growth",
              },
              {
                description: "Users by plan.",
                id: "plan_mix",
                label: "Plan Mix",
              },
            ],
          },
        };
      }

      if (path === "/admin/datasets/profile_growth") {
        return {
          data: {
            chartType: "line",
            description: "New users over time.",
            dimensionLabel: "Created Day",
            id: "profile_growth",
            label: "User Growth",
            metricLabel: "Users Created",
            points: [
              { label: "2026-04-20", value: 2 },
              { label: "2026-04-21", value: 4 },
            ],
          },
        };
      }

      if (path === "/admin/datasets/plan_mix") {
        return {
          data: {
            chartType: "donut",
            description: "Users by plan.",
            dimensionLabel: "Plan",
            id: "plan_mix",
            label: "Plan Mix",
            metricLabel: "Users",
            points: [
              { label: "solo", value: 6 },
              { label: "team", value: 3 },
            ],
          },
        };
      }

      throw new Error(`Unexpected path: ${path}`);
    });

    render(<AnalyticsStudioPage />);

    expect(await screen.findByText(/analytics studio/i)).toBeInTheDocument();
    expect(await screen.findByRole("button", { name: /user growth/i })).toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: /plan mix/i }));

    await waitFor(() => expect(adminApi.get).toHaveBeenCalledWith("/admin/datasets/plan_mix"));
    expect(await screen.findByText(/total/i)).toBeInTheDocument();
  });
});
