import { cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import { AgentMessageDetails } from "./agent-message-details";
import type { AgentQuestionInfo, AgentQuestionRequest } from "../types";

afterEach(cleanup);

describe("AgentMessageDetails question answers", () => {
  it("submits a custom answer instead of the selected option for a single-choice question", async () => {
    const user = userEvent.setup();
    const onReplyQuestion = vi.fn();

    renderQuestion(
      {
        header: "分析范围",
        question: "你想分析哪一部分？",
        options: [
          { label: "雨污混接分析", description: "检查混接问题" },
          { label: "水质异常分析", description: "检查水质指标" }
        ]
      },
      onReplyQuestion
    );

    await user.click(screen.getByRole("radio", { name: /雨污混接分析/ }));
    await user.click(screen.getByRole("radio", { name: "自定义回答" }));
    await user.type(screen.getByPlaceholderText("输入自定义回答"), "检查高峰时段压力");
    await user.click(screen.getByRole("button", { name: "提交回答" }));

    expect(onReplyQuestion).toHaveBeenCalledWith(
      expect.objectContaining({ requestId: "question-1" }),
      [["检查高峰时段压力"]]
    );
  });

  it("combines selected options with a custom answer for a multiple-choice question", async () => {
    const user = userEvent.setup();
    const onReplyQuestion = vi.fn();

    renderQuestion(
      {
        header: "分析内容",
        question: "需要包含哪些内容？",
        options: [
          { label: "压力", description: "分析节点压力" },
          { label: "流量", description: "分析管段流量" }
        ],
        multiple: true,
        custom: true
      },
      onReplyQuestion
    );

    await user.click(screen.getByRole("checkbox", { name: /压力/ }));
    await user.click(screen.getByRole("checkbox", { name: "自定义回答" }));
    await user.type(screen.getByPlaceholderText("输入自定义回答"), "补充水龄");
    await user.click(screen.getByRole("button", { name: "提交回答" }));

    expect(onReplyQuestion).toHaveBeenCalledWith(
      expect.objectContaining({ requestId: "question-1" }),
      [["压力", "补充水龄"]]
    );
  });
});

function renderQuestion(
  question: AgentQuestionInfo,
  onReplyQuestion: (request: AgentQuestionRequest, answers: string[][]) => void
) {
  render(
    <AgentMessageDetails
      message={{
        id: "assistant-1",
        role: "assistant",
        content: "需要补充信息",
        questions: [
          {
            requestId: "question-1",
            sessionId: "session-1",
            questions: [question],
            createdAt: 100,
            status: "pending"
          }
        ]
      }}
      onReplyQuestion={onReplyQuestion}
    />
  );
}
