import { act, fireEvent, render, screen } from "@testing-library/react";
import MonitoringPlaceOptimizationPanel, {
  getTabIndicatorSx,
  getTabIndicatorTransform,
} from "./MonitoringPlaceOptimizationPanel";
import { getSensorPlacementScheme } from "./schemeApi";
import type { SensorPlacementScheme } from "./types";

const mockSchemeEditorRender = jest.fn();

jest.mock("@refinedev/core", () => ({
  useNotification: () => ({ open: jest.fn() }),
}));

jest.mock("./OptimizationParameters", () => ({
  __esModule: true,
  default: () => <div>optimization parameters</div>,
  createOptimizationParametersState: () => ({}),
}));

jest.mock("./SchemeQuery", () => ({
  __esModule: true,
  default: ({ onEdit }: { onEdit: (schemeId: number) => void }) => (
    <button onClick={() => onEdit(7)}>打开测试方案</button>
  ),
  createMonitoringSchemeQueryState: () => ({}),
}));

jest.mock("./SchemeEditor", () => ({
  __esModule: true,
  default: ({
    scheme,
    active,
  }: {
    scheme: SensorPlacementScheme;
    active: boolean;
  }) => {
    mockSchemeEditorRender(active);
    return <div data-testid="scheme-editor">{scheme.scheme_name}</div>;
  },
}));

jest.mock("./schemeApi", () => ({
  getSensorPlacementScheme: jest.fn(),
}));

jest.mock("@components/olmap/common/PanelEmptyState", () => ({
  __esModule: true,
  default: () => <div>empty state</div>,
}));

const mockGetSensorPlacementScheme = jest.mocked(getSensorPlacementScheme);

const scheme: SensorPlacementScheme = {
  id: 7,
  scheme_name: "测试方案",
  sensor_number: 1,
  min_diameter: 100,
  username: "operator",
  create_time: "2026-07-30T08:00:00+08:00",
  sensor_location: ["J-1"],
  sensor_points: [],
  can_edit: true,
};

describe("MonitoringPlaceOptimizationPanel", () => {
  beforeEach(() => {
    mockSchemeEditorRender.mockClear();
  });

  it("applies equal-width positioning to the rendered tab indicator", () => {
    expect(getTabIndicatorTransform(0)).toBe("translateX(0%)");
    expect(getTabIndicatorTransform(1)).toBe("translateX(100%)");
    expect(getTabIndicatorTransform(2)).toBe("translateX(200%)");
    expect(getTabIndicatorSx(1)).toMatchObject({
      left: "0 !important",
      width: "33.333333% !important",
      transform: "translateX(100%)",
    });

    const { container } = render(<MonitoringPlaceOptimizationPanel />);
    const indicator = container.querySelector<HTMLElement>(
      ".MuiTabs-indicator",
    );

    expect(indicator).not.toBeNull();
    expect(indicator).toHaveStyle({ transform: "translateX(0%)" });

    fireEvent.click(screen.getByRole("tab", { name: /方案查询/ }));
    expect(indicator).toHaveStyle({ transform: "translateX(200%)" });
  });

  it("prepares a queried scheme before switching to the result editor", async () => {
    let resolveScheme: (value: SensorPlacementScheme) => void = () => {};
    mockGetSensorPlacementScheme.mockReturnValue(
      new Promise((resolve) => {
        resolveScheme = resolve;
      }),
    );

    render(<MonitoringPlaceOptimizationPanel />);

    const queryTab = screen.getByRole("tab", { name: /方案查询/ });
    const editorTab = screen.getByRole("tab", { name: /结果编辑/ });
    fireEvent.click(queryTab);
    fireEvent.click(screen.getByRole("button", { name: "打开测试方案" }));

    expect(queryTab).toHaveAttribute("aria-selected", "true");
    expect(editorTab).toHaveAttribute("aria-selected", "false");

    await act(async () => {
      resolveScheme(scheme);
      await Promise.resolve();
    });

    expect(editorTab).toHaveAttribute("aria-selected", "true");
    expect(screen.getByTestId("scheme-editor")).toBeVisible();
    expect(mockSchemeEditorRender.mock.calls.map(([active]) => active)).toEqual([
      false,
      true,
    ]);
  });
});
