"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { Button } from "@open-mercato/ui/primitives/button";
import { BooleanIcon } from "@open-mercato/ui/backend/ValueIcons";
import { apiCall, apiCallOrThrow, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { formatCategoryTreeLabel } from "../../lib/categoryTree.js";
const PAGE_SIZE = 50;
const TREE_BASE_INDENT = 18;
const TREE_STEP_INDENT = 14;
function computeIndent(depth) {
  if (depth <= 0) return 0;
  return TREE_BASE_INDENT + (depth - 1) * TREE_STEP_INDENT;
}
function CategoriesDataTable() {
  const t = useT();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const queryClient = useQueryClient();
  const scopeVersion = useOrganizationScopeVersion();
  const [page, setPage] = React.useState(1);
  const [status, setStatus] = React.useState("all");
  const [search, setSearch] = React.useState("");
  const [canManage, setCanManage] = React.useState(false);
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        const call = await apiCall("/api/auth/feature-check", {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ features: ["catalog.categories.manage"] })
        });
        if (!cancelled) {
          const granted = Array.isArray(call.result?.granted) ? call.result.granted : [];
          setCanManage(call.result?.ok === true || granted.includes("catalog.categories.manage"));
        }
      } catch {
        if (!cancelled) setCanManage(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, []);
  const queryParams = React.useMemo(() => {
    const params = new URLSearchParams();
    params.set("view", "manage");
    params.set("page", String(page));
    params.set("pageSize", String(PAGE_SIZE));
    params.set("status", status);
    if (search) params.set("search", search);
    return params.toString();
  }, [page, status, search]);
  const { data, isLoading } = useQuery({
    queryKey: ["catalog-categories", queryParams, scopeVersion],
    queryFn: async () => {
      const payload = await readApiResultOrThrow(
        `/api/catalog/categories?${queryParams}`,
        void 0,
        { errorMessage: t("catalog.categories.list.error.load", "Failed to load categories") }
      );
      return {
        items: Array.isArray(payload.items) ? payload.items : [],
        total: typeof payload.total === "number" ? payload.total : 0,
        page: typeof payload.page === "number" ? payload.page : 1,
        pageSize: typeof payload.pageSize === "number" ? payload.pageSize : PAGE_SIZE,
        totalPages: typeof payload.totalPages === "number" ? payload.totalPages : 1
      };
    }
  });
  const rows = data?.items ?? [];
  const total = data?.total ?? 0;
  const totalPages = data?.totalPages ?? 0;
  const columns = React.useMemo(() => [
    {
      accessorKey: "name",
      header: t("catalog.categories.list.columns.category", "Category"),
      meta: { priority: 1 },
      cell: ({ row }) => {
        const depth = row.original.depth ?? 0;
        return /* @__PURE__ */ jsx("div", { className: "flex items-center text-sm font-medium leading-none text-foreground", children: /* @__PURE__ */ jsx("span", { style: { marginLeft: computeIndent(depth), whiteSpace: "pre" }, children: formatCategoryTreeLabel(row.original.name, depth) }) });
      }
    },
    {
      accessorKey: "pathLabel",
      header: t("catalog.categories.list.columns.path", "Path"),
      meta: { priority: 3 },
      cell: ({ getValue }) => {
        const value = getValue();
        return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: value || "\u2014" });
      }
    },
    {
      accessorKey: "parentName",
      header: t("catalog.categories.list.columns.parent", "Parent"),
      meta: { priority: 4 },
      cell: ({ getValue }) => getValue() || t("catalog.categories.list.none", "\u2014")
    },
    {
      accessorKey: "childCount",
      header: t("catalog.categories.list.columns.children", "Children"),
      meta: { priority: 5 }
    },
    {
      accessorKey: "isActive",
      header: t("catalog.categories.list.columns.active", "Active"),
      enableSorting: false,
      meta: { priority: 2 },
      cell: ({ getValue }) => /* @__PURE__ */ jsx(BooleanIcon, { value: Boolean(getValue()) })
    }
  ], [t]);
  const handleDelete = React.useCallback(async (category) => {
    const confirmLabel = t(
      "catalog.categories.list.confirmDelete",
      'Archive category "{{name}}"?',
      { name: category.name }
    );
    const confirmed = await confirm({
      title: confirmLabel,
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await apiCallOrThrow(
        `/api/catalog/categories?id=${encodeURIComponent(category.id)}`,
        { method: "DELETE" },
        { errorMessage: t("catalog.categories.list.error.delete", "Failed to delete category") }
      );
      await queryClient.invalidateQueries({ queryKey: ["catalog-categories"] });
      flash(t("catalog.categories.flash.deleted", "Category archived"), "success");
    } catch (err) {
      const fallback = t("catalog.categories.list.error.delete", "Failed to delete category");
      const message = err instanceof Error ? err.message : fallback;
      flash(message, "error");
    }
  }, [confirm, queryClient, t]);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("catalog.categories.list.title", "Categories"),
        actions: canManage ? /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/catalog/categories/create", children: t("catalog.categories.list.actions.create", "Create") }) }) : void 0,
        columns,
        data: rows,
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("catalog.categories.list.title", "Categories"),
            createHref: canManage ? "/backend/catalog/categories/create" : void 0,
            createLabel: canManage ? t("catalog.categories.list.actions.create", "Create") : void 0
          }
        ),
        searchValue: search,
        searchPlaceholder: t("catalog.categories.list.searchPlaceholder", "Search categories"),
        onSearchChange: (value) => {
          setSearch(value);
          setPage(1);
        },
        filters: [
          {
            id: "status",
            label: t("catalog.categories.list.filters.status", "Status"),
            type: "select",
            options: [
              { value: "all", label: t("catalog.categories.list.filters.all", "All") },
              { value: "active", label: t("catalog.categories.list.filters.active", "Active") },
              { value: "inactive", label: t("catalog.categories.list.filters.inactive", "Inactive") }
            ]
          }
        ],
        filterValues: status === "all" ? {} : { status },
        onFiltersApply: (values) => {
          const nextStatus = values.status ?? "all";
          setStatus(nextStatus);
          setPage(1);
        },
        onFiltersClear: () => {
          setStatus("all");
          setPage(1);
        },
        sortable: false,
        perspective: { tableId: "catalog.categories.list" },
        rowActions: (row) => canManage ? /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              { id: "edit", label: t("catalog.categories.list.actions.edit", "Edit"), href: `/backend/catalog/categories/${row.id}/edit` },
              { id: "delete", label: t("catalog.categories.list.actions.delete", "Delete"), destructive: true, onSelect: () => handleDelete(row) }
            ]
          }
        ) : null,
        pagination: {
          page,
          pageSize: PAGE_SIZE,
          total,
          totalPages,
          onPageChange: setPage
        },
        isLoading
      }
    ),
    ConfirmDialogElement
  ] });
}
export {
  CategoriesDataTable as default
};
//# sourceMappingURL=CategoriesDataTable.js.map
