"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 RulesListPage() {
  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", "list", filterValues, page],
    queryFn: async () => {
      const params = new URLSearchParams();
      params.set("page", page.toString());
      params.set("pageSize", pageSize.toString());
      params.set("sortField", "priority");
      params.set("sortDir", "desc");
      if (filterValues.enabled) params.set("enabled", filterValues.enabled);
      if (filterValues.ruleType) params.set("ruleType", filterValues.ruleType);
      if (filterValues.entityType) params.set("entityType", filterValues.entityType);
      if (filterValues.eventType) params.set("eventType", filterValues.eventType);
      if (filterValues.search) params.set("search", filterValues.search);
      const result = await apiCall(
        `/api/business_rules/rules?${params.toString()}`
      );
      if (!result.ok) {
        throw new Error("Failed to fetch rules");
      }
      const response = result.result;
      if (response) {
        setTotal(response.total || 0);
        setTotalPages(response.totalPages || 1);
      }
      return response?.items || [];
    }
  });
  const handleDelete = async (id, ruleName) => {
    const confirmed = await confirm({
      title: t("business_rules.confirm.delete", { name: ruleName }),
      variant: "destructive"
    });
    if (!confirmed) return;
    const record = (data || []).find((item) => item.id === id);
    const result = await withScopedApiRequestHeaders(
      buildOptimisticLockHeader(record?.updatedAt),
      () => apiCall(`/api/business_rules/rules?id=${id}`, {
        method: "DELETE"
      })
    );
    if (result.ok) {
      flash(t("business_rules.messages.deleted"), "success");
      queryClient.invalidateQueries({ queryKey: ["business-rules"] });
    } else {
      flash(t("business_rules.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/rules", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id,
          enabled: !currentEnabled
        })
      })
    );
    if (result.ok) {
      flash(t("business_rules.messages.updated"), "success");
      queryClient.invalidateQueries({ queryKey: ["business-rules"] });
    } else {
      flash(t("business_rules.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.filters.searchPlaceholder")
    },
    {
      id: "enabled",
      type: "select",
      label: t("business_rules.filters.status"),
      options: [
        { label: t("common.all"), value: "" },
        { label: t("common.enabled"), value: "true" },
        { label: t("common.disabled"), value: "false" }
      ]
    },
    {
      id: "ruleType",
      type: "select",
      label: t("business_rules.filters.type"),
      options: [
        { label: t("common.all"), value: "" },
        { label: t("business_rules.types.guard"), value: "GUARD" },
        { label: t("business_rules.types.validation"), value: "VALIDATION" },
        { label: t("business_rules.types.calculation"), value: "CALCULATION" },
        { label: t("business_rules.types.action"), value: "ACTION" },
        { label: t("business_rules.types.assignment"), value: "ASSIGNMENT" }
      ]
    },
    {
      id: "entityType",
      type: "text",
      label: t("business_rules.filters.entityType"),
      placeholder: t("business_rules.filters.entityTypePlaceholder")
    },
    {
      id: "eventType",
      type: "text",
      label: t("business_rules.filters.eventType"),
      placeholder: t("business_rules.filters.eventTypePlaceholder")
    }
  ];
  const columns = [
    {
      id: "ruleId",
      header: t("business_rules.fields.ruleId"),
      accessorKey: "ruleId",
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-mono text-sm", children: row.original.ruleId })
    },
    {
      id: "ruleName",
      header: t("business_rules.fields.ruleName"),
      accessorKey: "ruleName",
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("div", { className: "font-medium", children: row.original.ruleName }),
        row.original.description && /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground line-clamp-1", children: row.original.description })
      ] })
    },
    {
      id: "ruleType",
      header: t("business_rules.fields.ruleType"),
      accessorKey: "ruleType",
      cell: ({ row }) => {
        const typeColors = {
          GUARD: "bg-status-error-bg text-status-error-text",
          VALIDATION: "bg-status-warning-bg text-status-warning-text",
          CALCULATION: "bg-status-info-bg text-status-info-text",
          ACTION: "bg-status-success-bg text-status-success-text",
          ASSIGNMENT: "bg-brand-violet/10 text-brand-violet"
        };
        const color = typeColors[row.original.ruleType] || "bg-muted text-foreground";
        return /* @__PURE__ */ jsx("span", { className: `inline-flex items-center px-2 py-1 rounded text-xs font-medium ${color}`, children: row.original.ruleType });
      }
    },
    {
      id: "entityType",
      header: t("business_rules.fields.entityType"),
      accessorKey: "entityType"
    },
    {
      id: "eventType",
      header: t("business_rules.fields.eventType"),
      accessorKey: "eventType",
      cell: ({ row }) => row.original.eventType || "-"
    },
    {
      id: "enabled",
      header: t("business_rules.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.actions.toggleEnabled"),
          children: row.original.enabled ? t("common.yes") : t("common.no")
        }
      )
    },
    {
      id: "priority",
      header: t("business_rules.fields.priority"),
      accessorKey: "priority",
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "font-mono text-sm", children: row.original.priority })
    },
    {
      id: "actions",
      header: "",
      cell: ({ row }) => /* @__PURE__ */ jsx(
        RowActions,
        {
          items: [
            {
              id: "edit",
              label: t("common.edit"),
              href: `/backend/rules/${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: "duplicate",
              label: t("common.duplicate"),
              onSelect: () => {
                flash(t("business_rules.messages.duplicateNotYetImplemented"), "info");
              }
            },
            {
              id: "delete",
              label: t("common.delete"),
              onSelect: () => handleDelete(row.original.id, row.original.ruleName),
              destructive: true
            }
          ]
        }
      )
    }
  ];
  if (error) {
    return /* @__PURE__ */ jsxs(Page, { children: [
      /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "p-8 text-center", children: [
        /* @__PURE__ */ jsx("p", { className: "text-status-error-text", children: t("business_rules.messages.loadFailed") }),
        /* @__PURE__ */ jsx(Button, { onClick: () => queryClient.invalidateQueries({ queryKey: ["business-rules"] }), className: "mt-4", children: t("common.retry") })
      ] }) }),
      ConfirmDialogElement
    ] });
  }
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("business_rules.list.title"),
        actions: /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/rules/create", children: t("business_rules.actions.create") }) }),
        columns,
        data: data || [],
        filters,
        filterValues,
        onFiltersApply: handleFiltersApply,
        onFiltersClear: handleFiltersClear,
        perspective: {
          tableId: "business-rules.rules.list"
        },
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("business_rules.list.title"),
            createHref: "/backend/rules/create",
            createLabel: t("business_rules.actions.create")
          }
        ),
        pagination: { page, pageSize, total, totalPages, onPageChange: setPage }
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  RulesListPage as default
};
//# sourceMappingURL=page.js.map
