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 lastQuery: Record<string, unknown> | null = null;
const mockUseHistory = vi.fn((query: Record<string, unknown>) => {
  console.log("mockUseHistory called", query);
  lastQuery = query;
  return {
    items: [],
    total: 0,
    page: 1,
    loading: false,
    error: null,
    setPage: vi.fn(),
    refresh: vi.fn(),
  };
});

vi.mock("../../hooks/useHistory", () => ({
  useHistory: (query: Record<string, unknown>) => mockUseHistory(query),
  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: async () => ({
    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 include the auto-applied default query.
    await waitFor(() => {
      expect(lastQuery).toEqual({
        range: "7d",
        source: "archive",
        origin: undefined,
        jail: undefined,
        ip: undefined,
        page: 1,
        page_size: 50,
      });
    });

    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(lastQuery).toMatchObject({ range: "7d" });
    });

    await user.click(screen.getByRole("button", { name: /Blocklist/i }));
    await waitFor(() => {
      expect(lastQuery).toMatchObject({ origin: "blocklist" });
    });
  });
});
