"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { DataTable, RowActions, Button } from "@open-mercato/ui";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { buildEntitiesCsv } from "../lib/entitiesCsvExport.js";
function buildColumns(t) {
  return [
    { accessorKey: "entityId", header: t("entities.user.table.column.entity", "Entity"), meta: { priority: 1 }, cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "font-mono", children: String(getValue()) }) },
    { accessorKey: "label", header: t("entities.user.table.column.label", "Label"), meta: { priority: 2 } },
    { accessorKey: "source", header: t("entities.user.table.column.source", "Source"), meta: { priority: 3 } },
    { accessorKey: "count", header: t("entities.user.table.column.fields", "Fields"), meta: { priority: 4 } },
    {
      accessorKey: "showInSidebar",
      header: t("entities.user.table.column.inSidebar", "In Sidebar"),
      meta: { priority: 5 },
      cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: `px-2 py-1 rounded text-xs ${getValue() ? "bg-status-success-bg text-status-success-text" : "bg-muted text-muted-foreground"}`, children: getValue() ? t("common.yes", "Yes") : t("common.no", "No") })
    }
  ];
}
function UserEntitiesTable() {
  const t = useT();
  const [sorting, setSorting] = React.useState([{ id: "entityId", desc: false }]);
  const [page, setPage] = React.useState(1);
  const [search, setSearch] = React.useState("");
  const scopeVersion = useOrganizationScopeVersion();
  const columns = React.useMemo(() => buildColumns(t), [t]);
  const { data, isLoading } = useQuery({
    queryKey: ["custom-entities", scopeVersion],
    queryFn: async () => {
      return readApiResultOrThrow("/api/entities/entities", void 0, {
        errorMessage: "Failed to load entities"
      });
    }
  });
  const rowsAll = data?.items || [];
  const userRows = rowsAll.filter((row) => row.source === "custom");
  const rows = React.useMemo(() => {
    if (!search) return userRows;
    const q = search.toLowerCase();
    return userRows.filter((r) => r.entityId.toLowerCase().includes(q) || r.label.toLowerCase().includes(q));
  }, [userRows, search]);
  return /* @__PURE__ */ jsx(
    DataTable,
    {
      title: t("entities.user.table.title", "User Entities"),
      actions: /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => {
          const csv = buildEntitiesCsv(rows, { includeSidebar: true });
          const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = url;
          a.download = "entities-user.csv";
          a.click();
          URL.revokeObjectURL(url);
        }, children: t("common.export", "Export") }),
        /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/entities/user/create", children: t("common.create", "Create") }) })
      ] }),
      columns,
      data: rows,
      searchValue: search,
      onSearchChange: (v) => {
        setSearch(v);
        setPage(1);
      },
      sortable: true,
      sorting,
      onSortingChange: setSorting,
      perspective: { tableId: "entities.user.list" },
      emptyState: /* @__PURE__ */ jsx(
        ListEmptyState,
        {
          entityName: t("entities.user.table.title", "User Entities"),
          createHref: "/backend/entities/user/create",
          createLabel: t("common.create", "Create")
        }
      ),
      rowActions: (row) => /* @__PURE__ */ jsx(
        RowActions,
        {
          items: [
            { id: "edit", label: t("common.edit", "Edit"), href: `/backend/entities/user/${encodeURIComponent(row.entityId)}` },
            { id: "show-records", label: t("entities.user.table.actions.showRecords", "Show records"), href: `/backend/entities/user/${encodeURIComponent(row.entityId)}/records` }
          ]
        }
      ),
      pagination: { page, pageSize: 50, total: rows.length, totalPages: 1, onPageChange: setPage },
      isLoading
    }
  );
}
export {
  UserEntitiesTable as default
};
//# sourceMappingURL=UserEntitiesTable.js.map
