import { describe, expect, test, vi } from "bun:test";
import { fireEvent, screen, waitFor } from "@testing-library/react";
import { createElement } from "react";

import type { Material } from "../../../../src/shared/api";

import { MaterialCard } from "../../../../src/web/features/inbox/components/MaterialCard";
import { renderWithProviders } from "../../test-utils";

const MOCK_MATERIAL: Material = {
  associatedDate: "2026-06-03",
  createdAt: "2026-06-03T00:00:00.000Z",
  description: "测试素材描述",
  id: "test-id",
  materialType: "general",
  processedContent: null,
  projectId: "project-1",
  status: "pending",
  updatedAt: "2026-06-03T00:00:00.000Z",
};

describe("MaterialCard", () => {
  test("渲染素材描述和状态标签", () => {
    renderWithProviders(
      createElement(MaterialCard, {
        material: MOCK_MATERIAL,
        onDelete: vi.fn(),
        onSelect: vi.fn(),
        selected: false,
      }),
    );
    expect(screen.getByText("测试素材描述")).not.toBeNull();
    expect(screen.getByText("待处理")).not.toBeNull();
  });

  test("点击卡片触发 onSelect", () => {
    const onSelect = vi.fn();
    renderWithProviders(
      createElement(MaterialCard, {
        material: MOCK_MATERIAL,
        onDelete: vi.fn(),
        onSelect,
        selected: false,
      }),
    );
    const item = screen.getByText("测试素材描述").closest(".app-sidebar-list-item")!;
    fireEvent.click(item);
    expect(onSelect).toHaveBeenCalledTimes(1);
  });

  test("点击删除按钮弹出确认框，确认后触发 onDelete", async () => {
    const onDelete = vi.fn();
    const onSelect = vi.fn();
    renderWithProviders(
      createElement(MaterialCard, {
        material: MOCK_MATERIAL,
        onDelete,
        onSelect,
        selected: false,
      }),
    );
    fireEvent.click(screen.getByLabelText("删除"));

    await waitFor(() => {
      expect(screen.getByText("确认删除该素材？")).not.toBeNull();
    });

    fireEvent.click(screen.getByText("删 除"));

    await waitFor(() => {
      expect(onDelete).toHaveBeenCalledTimes(1);
    });
    expect(onSelect).not.toHaveBeenCalled();
  });

  test("选中时包含 app-sidebar-list-item--selected 类名", () => {
    renderWithProviders(
      createElement(MaterialCard, {
        material: MOCK_MATERIAL,
        onDelete: vi.fn(),
        onSelect: vi.fn(),
        selected: true,
      }),
    );
    const item = screen.getByText("测试素材描述").closest(".app-sidebar-list-item--selected");
    expect(item).not.toBeNull();
  });

  test("未选中时不包含 app-sidebar-list-item--selected 类名", () => {
    renderWithProviders(
      createElement(MaterialCard, {
        material: MOCK_MATERIAL,
        onDelete: vi.fn(),
        onSelect: vi.fn(),
        selected: false,
      }),
    );
    const item = screen.getByText("测试素材描述").closest(".app-sidebar-list-item--selected");
    expect(item).toBeNull();
  });
});
