import { DataTable } from "@/shared/ui/DataTable.jsx";
import { createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";

export function LogTable({ data, isLogin, onQueryChange, pagination, query }) {
  const items = data.items || [];
  const columns = isLogin
    ? [
        {
          key: "username",
          label: "用户",
          width: "minmax(140px, 1fr)",
          filter: createTextColumnFilter({
            placeholder: "搜索用户、IP、动作、资源",
            value: query,
            onChange: onQueryChange
          })
        },
        { key: "ip", label: "IP", width: "minmax(140px, 1fr)", render: (item) => <span className="muted">{item.ip || "-"}</span> },
        { key: "status", label: "状态", width: "110px" },
        {
          key: "message",
          label: "消息",
          width: "minmax(220px, 1.5fr)",
          render: (item) => <span className="muted">{item.message || "-"}</span>
        },
        {
          key: "createdAt",
          label: "时间",
          width: "180px",
          render: (item) => <span className="muted">{formatMillis(item.createdAtMs ?? item.createdAt)}</span>
        }
      ]
    : [
        {
          key: "username",
          label: "用户",
          width: "minmax(140px, 1fr)",
          filter: createTextColumnFilter({
            placeholder: "搜索用户、IP、动作、资源",
            value: query,
            onChange: onQueryChange
          })
        },
        { key: "action", label: "动作", width: "minmax(120px, 1fr)" },
        {
          key: "resource",
          label: "资源",
          width: "minmax(160px, 1fr)",
          render: (item) => <span className="muted">{item.resource || "-"}</span>
        },
        { key: "status", label: "状态", width: "110px" },
        {
          key: "detail",
          label: "详情",
          width: "minmax(240px, 1.6fr)",
          render: (item) => <span className="muted">{item.detail || "-"}</span>
        },
        {
          key: "createdAt",
          label: "时间",
          width: "180px",
          render: (item) => <span className="muted">{formatMillis(item.createdAtMs ?? item.createdAt)}</span>
        }
      ];

  return (
    <DataTable
      columns={columns}
      items={items}
      minWidth={isLogin ? "920px" : "1080px"}
      pagination={pagination}
      rowKey={(item) => item.id}
    />
  );
}
