import { describe, expect, it, vi } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";

let lastCallArgs: unknown[] | null = null;
const mockUseHistory = vi.fn((...args: unknown[]) => {
  lastCallArgs = args;
  return {
    items: [],
    total: 0,
    page: 1,
    loading: false,
    error: null,
    setPage: vi.fn(),
    refresh: vi.fn(),
  };
});

vi.mock("../../hooks/useHistory", () => ({
  useHistory: (...args: unknown[]) => mockUseHistory(...args),
  useIpHistory: () => ({ detail: null, loading: false, error: null, refresh: vi.fn() }),
}));

vi.mock("../../components/WorldMap", () => ({
  WorldMap: () => <div data-testid="world-map" />,
}));

vi.mock("../../api/config", () => ({
  fetchMapColorThresholds: () => ({
    threshold_low: 10,
    threshold_medium: 50,
    threshold_high: 100,
  }),
}));

import { HistoryPage } from "../HistoryPage";

describe("HistoryPage", () => {
  it("auto-applies filters on change and hides apply/clear actions", async () => {
    const user = userEvent.setup();

    render(
      <FluentProvider theme={webLightTheme}>
        <HistoryPage />
      </FluentProvider>,
    );

    // Initial load should have default parameters: page, pageSize, range, origin, jail, ip, source
    // Arguments: (page: 1, pageSize: 50, range: "7d", origin: undefined, jail: undefined, ip: undefined, source: "archive")
    await waitFor(() => {
      expect(lastCallArgs).toEqual([
        1, // page
        50, // pageSize
        "7d", // range
        undefined, // origin
        undefined, // jail
        undefined, // ip
        "archive", // source
      ]);
    });

    expect(screen.queryByRole("button", { name: /apply/i })).toBeNull();
    expect(screen.queryByRole("button", { name: /clear/i })).toBeNull();

    // Time-range and origin updates should be applied automatically.
    await user.click(screen.getByRole("button", { name: /Last 7 days/i }));
    await waitFor(() => {
      expect(lastCallArgs?.[2]).toBe("7d"); // range is at index 2
    });

    await user.click(screen.getByRole("button", { name: /Blocklist/i }));
    await waitFor(() => {
      expect(lastCallArgs?.[3]).toBe("blocklist"); // origin is at index 3
    });
  });

  it("never calls history without the default range on mount", async () => {
    render(
      <FluentProvider theme={webLightTheme}>
        <HistoryPage />
      </FluentProvider>,
    );

    await waitFor(() => {
      expect(lastCallArgs?.[2]).toBe("7d"); // range is at index 2
    });

    expect(mockUseHistory.mock.calls.every((call) => call[2] === "7d")).toBe(true);
  });
});
