import { fireEvent, render, screen } from "@testing-library/react";
import BurstPipeAnalysisPanel from "./BurstPipeAnalysisPanel";

jest.mock("./AnalysisParameters", () => ({
  __esModule: true,
  default: () => <div>analysis parameters</div>,
  createBurstAnalysisParametersState: () => ({}),
}));

jest.mock("./SchemeQuery", () => ({
  __esModule: true,
  default: ({
    onViewReport,
  }: {
    onViewReport: (scheme: Record<string, unknown>) => void;
  }) => {
    const createScheme = (id: number, schemeName: string) => ({
      id,
      schemeName,
      type: "burst_analysis",
      username: "operator",
      create_time: "2026-07-30T08:00:00+08:00",
      startTime: "2026-07-30T09:00:00+08:00",
      schemeDetail: {
        burst_ID: ["P-1", "P-2"],
        burst_size: [120, 80],
      },
    });

    return (
      <>
        <button onClick={() => onViewReport(createScheme(1, "selected-scheme"))}>
          mock report action
        </button>
        <button onClick={() => onViewReport(createScheme(2, "other-scheme"))}>
          mock other report action
        </button>
      </>
    );
  },
  createBurstSchemeQueryState: () => ({}),
}));

jest.mock("./AnalysisReport", () => ({
  __esModule: true,
  default: ({
    scheme,
    valveResult,
  }: {
    scheme: { schemeName: string } | null;
    valveResult: { accident_elements: string[] } | null;
  }) => (
    <div>
      report:{scheme?.schemeName ?? "empty"}:valve:
      {valveResult?.accident_elements.join(",") ?? "none"}
    </div>
  ),
  matchesValveAnalysis: (
    scheme: { schemeDetail: { burst_ID: string[] } },
    valveResult: { accident_elements: string[] } | null,
  ) =>
    valveResult !== null &&
    valveResult.accident_elements.every((pipeId) =>
      scheme.schemeDetail.burst_ID.includes(pipeId),
    ),
}));

jest.mock("./ValveIsolation", () => ({
  __esModule: true,
  default: ({
    allowedPipeIds,
    sourceSchemeName,
    onResultChange,
  }: {
    allowedPipeIds?: string[];
    sourceSchemeName?: string;
    onResultChange: (result: Record<string, unknown>) => void;
  }) => (
    <>
      <div data-testid="valve-scope">
        valve scope:{sourceSchemeName ?? "independent"}:
        {allowedPipeIds?.join(",") ?? "any"}
      </div>
      <button
        onClick={() =>
          onResultChange({
            accident_elements: ["P-1"],
            affected_nodes: ["J-1"],
            must_close_valves: ["V-1"],
            optional_valves: [],
            isolatable: true,
          })
        }
      >
        mock valve result
      </button>
    </>
  ),
  createValveIsolationState: () => ({
    selectedPipeId: null,
    activeStep: 0,
    expandedResult: true,
    disabledValves: [],
  }),
}));

describe("BurstPipeAnalysisPanel", () => {
  it("replaces the obsolete location tab and opens the selected report", () => {
    render(<BurstPipeAnalysisPanel />);

    expect(
      screen.queryByRole("tab", { name: /定位结果/ }),
    ).not.toBeInTheDocument();
    expect(
      screen.getByRole("tab", { name: /分析报告/ }),
    ).toBeInTheDocument();

    fireEvent.click(screen.getByRole("tab", { name: /方案查询/ }));
    fireEvent.click(
      screen.getByRole("button", { name: "mock report action" }),
    );

    expect(
      screen.getByText("report:selected-scheme:valve:none"),
    ).toBeInTheDocument();

    fireEvent.click(screen.getByRole("tab", { name: /关阀分析/ }));
    expect(screen.getByTestId("valve-scope")).toHaveTextContent(
      "valve scope:selected-scheme:P-1,P-2",
    );
  });

  it("does not reuse valve results across schemes with the same pipe", () => {
    render(<BurstPipeAnalysisPanel />);

    fireEvent.click(screen.getByRole("tab", { name: /方案查询/ }));
    fireEvent.click(
      screen.getByRole("button", { name: "mock report action" }),
    );
    fireEvent.click(screen.getByRole("tab", { name: /关阀分析/ }));
    fireEvent.click(
      screen.getByRole("button", { name: "mock valve result" }),
    );

    fireEvent.click(screen.getByRole("tab", { name: /方案查询/ }));
    fireEvent.click(
      screen.getByRole("button", { name: "mock other report action" }),
    );

    expect(
      screen.getByText("report:other-scheme:valve:none"),
    ).toBeInTheDocument();
  });
});
