"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable } from "@open-mercato/ui/backend/DataTable";
import { Button } from "@open-mercato/ui/primitives/button";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
function RuleSetsListPage() {
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(20);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const t = useT();
  const router = useRouter();
  const queryClient = useQueryClient();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [filterValues, setFilterValues] = React.useState({});
  const { data, isLoading, error } = useQuery({
    queryKey: ["business-rules", "sets", filterValues, page],
    queryFn: async () => {
      const params = new URLSearchParams();
      params.set("page", page.toString());
      params.set("pageSize", pageSize.toString());
      params.set("sortField", "setName");
      params.set("sortDir", "asc");
      if (filterValues.enabled) params.set("enabled", filterValues.enabled);
      if (filterValues.search) params.set("search", filterValues.search);
      const result = await apiCall(
        `/api/business_rules/sets?${params.toString()}`
      );
      if (!result.ok) {
        throw new Error("Failed to fetch rule sets");
      }
      const response = result.result;
      if (response) {
        setTotal(response.total || 0);
        setTotalPages(response.totalPages || 1);
      }
      return response?.items || [];
    }
  });
  const handleDelete = async (id, setName) => {
    const confirmed = await confirm({
      title: t("business_rules.sets.confirm.delete", { name: setName }),
      variant: "destructive"
    });
    if (!confirmed) return;
    const record = (data || []).find((item) => item.id === id);
    const result = await withScopedApiRequestHeaders(
      buildOptimisticLockHeader(record?.updatedAt),
      () => apiCall(`/api/business_rules/sets?id=${id}`, {
        method: "DELETE"
      })
    );
    if (result.ok) {
      flash(t("business_rules.sets.messages.deleted"), "success");
      queryClient.invalidateQueries({ queryKey: ["business-rules", "sets"] });
    } else {
      flash(t("business_rules.sets.messages.deleteFailed"), "error");
    }
  };
  const handleToggleEnabled = async (id, currentEnabled) => {
    const record = (data || []).find((item) => item.id === id);
    const result = await withScopedApiRequestHeaders(
      buildOptimisticLockHeader(record?.updatedAt),
      () => apiCall("/api/business_rules/sets", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id,
          enabled: !currentEnabled
        })
      })
    );
    if (result.ok) {
      flash(t("business_rules.sets.messages.updated"), "success");
      queryClient.invalidateQueries({ queryKey: ["business-rules", "sets"] });
    } else {
      flash(t("business_rules.sets.messages.updateFailed"), "error");
    }
  };
  const handleFiltersApply = React.useCallback((values) => {
    const next = {};
    Object.entries(values).forEach(([key, value]) => {
      if (value !== void 0) next[key] = value;
    });
    setFilterValues(next);
    setPage(1);
  }, [setFilterValues, setPage]);
  const handleFiltersClear = React.useCallback(() => {
    setFilterValues({});
    setPage(1);
  }, [setFilterValues, setPage]);
  const filters = [
    {
      id: "search",
      type: "text",
      label: t("business_rules.filters.search"),
      placeholder: t("business_rules.sets.filters.searchPlaceholder")
    },
    {
      id: "enabled",
      type: "select",
      label: t("business_rules.filters.status"),
      options: [
        { value: "", label: t("common.all") },
        { value: "true", label: t("common.enabled") },
        { value: "false", label: t("common.disabled") }
      ]
    }
  ];
  const columns = [
    {
      id: "setId",
      header: t("business_rules.sets.fields.setId"),
      accessorKey: "setId",
      cell: ({ row }) => /* @__PURE__ */ jsx(
        Link,
        {
          href: `/backend/sets/${row.original.id}`,
          className: "font-mono text-sm text-primary hover:underline",
          children: row.original.setId
        }
      )
    },
    {
      id: "setName",
      header: t("business_rules.sets.fields.setName"),
      accessorKey: "setName",
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("div", { className: "font-medium", children: row.original.setName }),
        row.original.description && /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground mt-0.5 line-clamp-1", children: row.original.description })
      ] })
    },
    {
      id: "enabled",
      header: t("business_rules.sets.fields.enabled"),
      accessorKey: "enabled",
      cell: ({ row }) => /* @__PURE__ */ jsx(
        "button",
        {
          onClick: () => handleToggleEnabled(row.original.id, row.original.enabled),
          className: `inline-flex items-center px-2 py-1 rounded text-xs font-medium cursor-pointer ${row.original.enabled ? "bg-status-success-bg text-status-success-text hover:bg-status-success-bg/80" : "bg-muted text-muted-foreground hover:bg-muted/50"}`,
          title: t("business_rules.sets.actions.toggleEnabled"),
          children: row.original.enabled ? t("common.yes") : t("common.no")
        }
      )
    },
    {
      id: "actions",
      header: "",
      cell: ({ row }) => /* @__PURE__ */ jsx(
        RowActions,
        {
          items: [
            {
              id: "edit",
              label: t("common.edit"),
              href: `/backend/sets/${row.original.id}`
            },
            {
              id: row.original.enabled ? "disable" : "enable",
              label: row.original.enabled ? t("common.disable") : t("common.enable"),
              onSelect: () => handleToggleEnabled(row.original.id, row.original.enabled)
            },
            {
              id: "delete",
              label: t("common.delete"),
              onSelect: () => handleDelete(row.original.id, row.original.setName),
              destructive: true
            }
          ]
        }
      )
    }
  ];
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("business_rules.sets.list.title"),
        actions: /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/sets/create", children: t("business_rules.sets.actions.create") }) }),
        columns,
        data: data || [],
        filters,
        filterValues,
        onFiltersApply: handleFiltersApply,
        onFiltersClear: handleFiltersClear,
        isLoading,
        error: error ? t("business_rules.sets.messages.loadFailed") : void 0,
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("business_rules.sets.list.title"),
            createHref: "/backend/sets/create",
            createLabel: t("business_rules.sets.actions.create")
          }
        ),
        pagination: { page, pageSize, total, totalPages, onPageChange: setPage }
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  RuleSetsListPage as default
};
//# sourceMappingURL=page.js.map
