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("shows skeleton rows while history sessions are loading", () => {
    renderWithTheme(
      <AgentHistoryPanel
        sessions={[]}
        isLoadingSessions
        onNewSession={jest.fn()}
        onRenameSession={jest.fn()}
        onSelectSession={jest.fn()}
        onDeleteSession={jest.fn()}
      />,
    );

    expect(screen.getByLabelText("正在加载历史会话")).toBeInTheDocument();
    expect(screen.queryByText("暂无历史会话")).not.toBeInTheDocument();
  });

  it("disables the loading history session item", () => {
    const onSelectSession = jest.fn();
    const onRenameSession = jest.fn();
    const onDeleteSession = jest.fn();

    renderWithTheme(
      <AgentHistoryPanel
        sessions={[
          {
            id: "session-loading",
            title: "正在加载的会话",
            createdAt: Date.now(),
            updatedAt: Date.now(),
          },
        ]}
        loadingSessionId="session-loading"
        onNewSession={jest.fn()}
        onRenameSession={onRenameSession}
        onSelectSession={onSelectSession}
        onDeleteSession={onDeleteSession}
      />,
    );

    expect(screen.queryByText("正在加载的会话")).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: "修改会话标题" })).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: "删除会话" })).not.toBeInTheDocument();

    fireEvent.click(screen.getByLabelText("正在加载会话 正在加载的会话"));

    expect(onSelectSession).not.toHaveBeenCalled();
    expect(onRenameSession).not.toHaveBeenCalled();
    expect(onDeleteSession).not.toHaveBeenCalled();
  });

  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(["较新的首条消息", "较新的更新"]);
  });
});
