import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, expect, test } from "vitest";
import { TimeZoneProvider, useTimeZone } from "@/app/timezone/TimeZoneProvider.jsx";
import { formatMillis } from "@/shared/utils/time.js";
import { DataTable } from "./DataTable.jsx";

const epochMillis = Date.UTC(2026, 4, 9, 19, 21, 0);

beforeEach(() => {
  window.localStorage.clear();
});

test("rerenders table timestamp cells when display timezone changes", async () => {
  const user = userEvent.setup();

  render(
    <TimeZoneProvider>
      <TimezoneTableFixture />
    </TimeZoneProvider>
  );

  expect(screen.getByText("2026-05-10 03:21:00")).toBeInTheDocument();

  await user.click(screen.getByRole("button", { name: "UTC" }));

  expect(screen.getByText("2026-05-09 19:21:00")).toBeInTheDocument();
});

test("only shows the table filter reset action when filters are active", () => {
  const columns = [
    {
      filter: { onChange: () => {}, type: "text", value: "" },
      key: "name",
      label: "名称"
    },
    {
      key: "actions",
      label: "操作"
    }
  ];

  const { rerender } = render(
    <TimeZoneProvider>
      <DataTable columns={columns} items={[{ id: 1, name: "Banner" }]} rowKey={(item) => item.id} />
    </TimeZoneProvider>
  );

  expect(screen.queryByRole("button", { name: "重置筛选" })).not.toBeInTheDocument();

  rerender(
    <TimeZoneProvider>
      <DataTable
        columns={[{ ...columns[0], filter: { ...columns[0].filter, value: "Banner" } }, columns[1]]}
        items={[{ id: 1, name: "Banner" }]}
        rowKey={(item) => item.id}
      />
    </TimeZoneProvider>
  );

  expect(screen.getByRole("button", { name: "重置筛选" })).toBeInTheDocument();
});

test("expands table background to the minimum width required by columns", () => {
  const columns = [
    { key: "user", label: "用户", width: "minmax(220px, 1fr)" },
    { key: "createdAt", label: "创建时间", width: "minmax(180px, 1fr)" },
    { key: "actions", label: "操作" }
  ];

  render(
    <TimeZoneProvider>
      <DataTable columns={columns} items={[{ createdAt: "2026-06-15", id: 1, user: "admin" }]} minWidth="300px" rowKey={(item) => item.id} />
    </TimeZoneProvider>
  );

  expect(document.querySelector(".admin-table")?.style.getPropertyValue("--admin-table-content-width")).toBe("512px");
});

function TimezoneTableFixture() {
  const { setTimeZone } = useTimeZone();
  const columns = [
    {
      key: "createdAtMs",
      label: "创建时间",
      render: (item) => formatMillis(item.createdAtMs)
    }
  ];

  return (
    <>
      <button type="button" onClick={() => setTimeZone("UTC")}>
        UTC
      </button>
      <DataTable columns={columns} items={[{ createdAtMs: epochMillis, id: 1 }]} rowKey={(item) => item.id} />
    </>
  );
}
