import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import { MemoryRouter } from "react-router-dom";
import { ConfigPage } from "../ConfigPage";

// Mock all tab components to avoid deep render trees and API calls.
vi.mock("../../components/config", () => ({
  JailsTab: ({ initialJail }: { initialJail?: string }) => (
    <div data-testid="jails-tab" data-initial-jail={initialJail}>
      JailsTab
    </div>
  ),
  FiltersTab: () => <div data-testid="filters-tab">FiltersTab</div>,
  ActionsTab: () => <div data-testid="actions-tab">ActionsTab</div>,
  ServerTab: () => <div data-testid="server-tab">ServerTab</div>,
  RegexTesterTab: () => <div data-testid="regex-tab">RegexTesterTab</div>,
  ExportTab: () => <div data-testid="export-tab">ExportTab</div>,
}));

function renderPage() {
  return render(
    <MemoryRouter>
      <FluentProvider theme={webLightTheme}>
        <ConfigPage />
      </FluentProvider>
    </MemoryRouter>,
  );
}

describe("ConfigPage", () => {
  it("renders the Jails tab by default", () => {
    renderPage();
    expect(screen.getByTestId("jails-tab")).toBeInTheDocument();
  });

  it("switches to Filters tab when Filters tab is clicked", () => {
    renderPage();
    fireEvent.click(screen.getByRole("tab", { name: /filters/i }));
    expect(screen.getByTestId("filters-tab")).toBeInTheDocument();
    expect(screen.queryByTestId("jails-tab")).not.toBeInTheDocument();
  });

  it("switches to Actions tab when Actions tab is clicked", () => {
    renderPage();
    fireEvent.click(screen.getByRole("tab", { name: /actions/i }));
    expect(screen.getByTestId("actions-tab")).toBeInTheDocument();
  });

  it("switches to Server tab when Server tab is clicked", () => {
    renderPage();
    fireEvent.click(screen.getByRole("tab", { name: /server/i }));
    expect(screen.getByTestId("server-tab")).toBeInTheDocument();
  });

  it("renders the page heading", () => {
    renderPage();
    expect(screen.getByRole("heading", { name: /configuration/i })).toBeInTheDocument();
  });

  it("selects the Jails tab based on location state", () => {
    render(
      <MemoryRouter
        initialEntries={[
          { pathname: "/config", state: { tab: "jails", jail: "sshd" } },
        ]}
      >
        <FluentProvider theme={webLightTheme}>
          <ConfigPage />
        </FluentProvider>
      </MemoryRouter>,
    );

    const jailsTab = screen.getByTestId("jails-tab");
    expect(jailsTab).toBeInTheDocument();
    expect(jailsTab).toHaveAttribute("data-initial-jail", "sshd");
  });
});
