import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import type {
  WorkbenchMapCommands,
  WorkbenchMapControllerState
} from "../map/workbench-map-controller";
import { MapDevPanel } from "./map-dev-panel";

afterEach(cleanup);

describe("MapDevPanel flow controls", () => {
  it("updates a pipe with its signed velocity", async () => {
    const user = userEvent.setup();
    const commands = createCommands();

    render(
      <MapDevPanel
        commands={commands}
        controllerState={createControllerState()}
        detailFeature={null}
        onClose={vi.fn()}
      />
    );

    const pipeId = screen.getByLabelText("管道 ID");
    const velocity = screen.getByLabelText("有符号流速");
    await user.clear(pipeId);
    await user.type(pipeId, "P-9");
    await user.clear(velocity);
    await user.type(velocity, "-2.75");
    await user.click(screen.getByRole("button", { name: "更新该管道方向" }));

    expect(commands.updatePipeFlowCalculation).toHaveBeenCalledWith({
      pipeId: "P-9",
      velocity: -2.75
    });
  });

  it("shows the current flow direction counts", () => {
    render(
      <MapDevPanel
        commands={createCommands()}
        controllerState={createControllerState({
          flowSummary: {
            total: 4,
            forward: 2,
            reverse: 1,
            stopped: 1,
            invalid: 0
          }
        })}
        detailFeature={null}
        onClose={vi.fn()}
      />
    );

    expect(screen.getByRole("status", {
      name: ""
    })).toHaveTextContent("已赋值 4 · 正向 2 · 反向 1 · 停止 1");
  });
});

function createCommands() {
  return {
    zoomToFeature: vi.fn(),
    locateAndHighlight: vi.fn(),
    highlight: vi.fn(),
    clearHighlight: vi.fn(),
    setFlowVisible: vi.fn(),
    replacePipeFlowCalculations: vi.fn(),
    updatePipeFlowCalculation: vi.fn(),
    clearPipeFlowCalculations: vi.fn(),
    showValueLabel: vi.fn(),
    clearValueLabel: vi.fn(),
    applyLayerGroupStyle: vi.fn(),
    resetLayerGroupStyle: vi.fn(),
    renderScadaAnalysis: vi.fn(),
    clearScadaAnalysis: vi.fn(),
    resetAll: vi.fn()
  } satisfies WorkbenchMapCommands;
}

function createControllerState(
  patch: Partial<WorkbenchMapControllerState> = {}
): WorkbenchMapControllerState {
  return {
    target: null,
    valueLabels: {},
    pending: false,
    errorCode: null,
    flowVisible: false,
    flowSummary: {
      total: 0,
      forward: 0,
      reverse: 0,
      stopped: 0,
      invalid: 0
    },
    styledGroups: [],
    scadaAnalysis: null,
    ...patch
  };
}
