import { fireEvent, render, screen } from "@testing-library/react";
import { expect, test, vi } from "vitest";
import { FinanceMyApplicationList } from "./FinanceMyApplicationList.jsx";

const baseProps = {
  applications: {
    items: [],
    page: 1,
    pageSize: 50,
    total: 0
  },
  error: "",
  filters: {
    appCode: "",
    keyword: "",
    operation: "",
    page: 1,
    status: ""
  },
  loading: false,
  onCreate: vi.fn(),
  onFiltersChange: vi.fn(),
  onReload: vi.fn(),
  operations: [{ label: "增加用户金币", value: "user_coin_credit" }],
  options: { apps: [] }
};

test("renders my finance application list and create action", () => {
  const onCreate = vi.fn();
  render(
    <FinanceMyApplicationList
      {...baseProps}
      applications={{
        ...baseProps.applications,
        items: [
          {
            appCode: "lalu",
            auditedAtMs: 1760007200000,
            auditorName: "财务一",
            auditorUserId: 21,
            coinAmount: 100,
            createdAtMs: 1760000000000,
            credentialText: "receipt",
            id: 7,
            operation: "user_coin_credit",
            rechargeAmount: 12.5,
            status: "approved",
            targetUserId: "10001"
          }
        ],
        total: 1
      }}
      onCreate={onCreate}
    />
  );

  expect(screen.getByRole("columnheader", { name: "APP" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "操作" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "目标用户" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "金币数量" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "充值金额" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "凭证" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "状态" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "发起申请时间" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "审批人" })).toBeInTheDocument();
  expect(screen.getByRole("columnheader", { name: "审核时间" })).toBeInTheDocument();
  expect(screen.getByText("lalu")).toBeInTheDocument();
  expect(screen.getByText("增加用户金币")).toBeInTheDocument();
  expect(screen.getByText("10001")).toBeInTheDocument();
  expect(screen.getByText("已通过")).toBeInTheDocument();

  fireEvent.click(screen.getByRole("button", { name: "添加" }));
  expect(onCreate).toHaveBeenCalledTimes(1);
});

test("keeps empty my finance application table colspan aligned with visible columns", () => {
  const { container } = render(<FinanceMyApplicationList {...baseProps} />);

  expect(container.querySelector("tbody td")?.colSpan).toBe(10);
  expect(screen.getByText("当前无数据")).toBeInTheDocument();
});
