import React from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import { ThemeProvider, createTheme } from "@mui/material/styles";

import { AgentHistoryPanel } from "./AgentHistoryPanel";

const renderWithTheme = (ui: React.ReactElement) =>
  render(<ThemeProvider theme={createTheme()}>{ui}</ThemeProvider>);

describe("AgentHistoryPanel", () => {
  it("renames a history session from the list", () => {
    const onRenameSession = jest.fn();

    renderWithTheme(
      <AgentHistoryPanel
        sessions={[
          {
            id: "session-1",
            title: "旧会话标题",
            createdAt: Date.now(),
            updatedAt: Date.now(),
          },
        ]}
        activeSessionId="session-1"
        onNewSession={jest.fn()}
        onRenameSession={onRenameSession}
        onSelectSession={jest.fn()}
        onDeleteSession={jest.fn()}
      />,
    );

    fireEvent.click(screen.getByRole("button", { name: "修改会话标题" }));
    fireEvent.change(screen.getByPlaceholderText("请输入会话标题"), {
      target: { value: "新的会话标题" },
    });
    fireEvent.click(screen.getByLabelText("确认"));

    expect(onRenameSession).toHaveBeenCalledWith("session-1", "新的会话标题");
  });

  it("orders history by the first message time instead of the latest update time", () => {
    renderWithTheme(
      <AgentHistoryPanel
        sessions={[
          {
            id: "session-newer-update",
            title: "较新的更新",
            createdAt: new Date("2026-05-18T09:00:00+08:00").getTime(),
            updatedAt: new Date("2026-05-19T12:00:00+08:00").getTime(),
          },
          {
            id: "session-newer-first-message",
            title: "较新的首条消息",
            createdAt: new Date("2026-05-19T08:00:00+08:00").getTime(),
            updatedAt: new Date("2026-05-19T08:30:00+08:00").getTime(),
          },
        ]}
        onNewSession={jest.fn()}
        onRenameSession={jest.fn()}
        onSelectSession={jest.fn()}
        onDeleteSession={jest.fn()}
      />,
    );

    const sessionTitles = screen.getAllByText(/较新的/).map((element) => element.textContent);

    expect(sessionTitles).toEqual(["较新的首条消息", "较新的更新"]);
  });
});
