"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 { Badge } from "@open-mercato/ui/primitives/badge";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { apiCall, readApiResultOrThrow, 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 { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { ListEmptyState } from "@open-mercato/ui/backend/filters/ListEmptyState";
function CustomerRolesPage() {
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const t = useT();
  const router = useRouter();
  const [rows, setRows] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [pageSize] = React.useState(50);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const [search, setSearch] = React.useState("");
  const [isLoading, setIsLoading] = React.useState(true);
  const [reloadToken, setReloadToken] = React.useState(0);
  const { runMutation } = useGuardedMutation({
    contextId: "customer_accounts:roles-list"
  });
  const runMutationWithContext = React.useCallback(
    async (operation, mutationPayload) => {
      return runMutation({
        operation,
        mutationPayload,
        context: { entityType: "customer_accounts:role" }
      });
    },
    [runMutation]
  );
  const queryParams = React.useMemo(() => {
    const params = new URLSearchParams();
    params.set("page", String(page));
    params.set("pageSize", String(pageSize));
    if (search.trim()) params.set("search", search.trim());
    return params.toString();
  }, [page, pageSize, search]);
  React.useEffect(() => {
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      try {
        const fallback = { items: [], total: 0, totalPages: 1 };
        const payload = await readApiResultOrThrow(
          `/api/customer_accounts/admin/roles?${queryParams}`,
          void 0,
          { errorMessage: t("customer_accounts.admin.roles.error.load", "Failed to load roles"), fallback }
        );
        if (cancelled) return;
        const items = Array.isArray(payload?.items) ? payload.items : [];
        setRows(items);
        setTotal(typeof payload?.total === "number" ? payload.total : items.length);
        setTotalPages(typeof payload?.totalPages === "number" ? payload.totalPages : 1);
      } catch (err) {
        if (!cancelled) {
          const message = err instanceof Error ? err.message : t("customer_accounts.admin.roles.error.load", "Failed to load roles");
          flash(message, "error");
        }
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [queryParams, reloadToken, t]);
  const handleDelete = React.useCallback(async (role) => {
    if (role.isDefault) {
      flash(t("customer_accounts.admin.roles.error.deleteDefault", "The default role cannot be deleted. Set another role as default first."), "error");
      return;
    }
    const confirmed = await confirm({
      title: t("customer_accounts.admin.roles.confirm.delete", 'Delete role "{{name}}"?', { name: role.name }),
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await runMutationWithContext(async () => {
        const call = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(role.updatedAt),
          () => apiCall(
            `/api/customer_accounts/admin/roles/${encodeURIComponent(role.id)}`,
            { method: "DELETE" }
          )
        );
        if (!call.ok) {
          flash(t("customer_accounts.admin.roles.error.delete", "Failed to delete role"), "error");
          return;
        }
        flash(t("customer_accounts.admin.roles.flash.deleted", "Role deleted"), "success");
        setReloadToken((token) => token + 1);
      }, { id: role.id });
    } catch (err) {
      const message = err instanceof Error ? err.message : t("customer_accounts.admin.roles.error.delete", "Failed to delete role");
      flash(message, "error");
    }
  }, [confirm, runMutationWithContext, t]);
  const columns = React.useMemo(() => [
    {
      accessorKey: "name",
      header: t("customer_accounts.admin.roles.columns.name", "Name"),
      cell: ({ row }) => /* @__PURE__ */ jsx(
        Link,
        {
          href: `/backend/customer_accounts/roles/${row.original.id}`,
          className: "font-medium hover:underline",
          children: row.original.name
        }
      )
    },
    {
      accessorKey: "slug",
      header: t("customer_accounts.admin.roles.columns.slug", "Slug"),
      cell: ({ row }) => /* @__PURE__ */ jsx("code", { className: "rounded bg-muted px-1.5 py-0.5 text-xs", children: row.original.slug })
    },
    {
      accessorKey: "description",
      header: t("customer_accounts.admin.roles.columns.description", "Description"),
      cell: ({ row }) => row.original.description || /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "-" })
    },
    {
      accessorKey: "isSystem",
      header: t("customer_accounts.admin.roles.columns.isSystem", "System"),
      cell: ({ row }) => row.original.isSystem ? /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-status-info-bg px-2 py-0.5 text-xs font-medium text-status-info-text", children: t("customer_accounts.admin.roles.system", "System") }) : null
    },
    {
      accessorKey: "isDefault",
      header: t("customer_accounts.admin.roles.columns.isDefault", "Default"),
      cell: ({ row }) => row.original.isDefault ? /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-status-success-bg px-2 py-0.5 text-xs font-medium text-status-success-text", children: t("customer_accounts.admin.roles.default", "Default") }) : null
    },
    {
      accessorKey: "customerAssignable",
      header: t("customer_accounts.admin.roles.columns.customerAssignable", "Self-assignable"),
      cell: ({ row }) => row.original.customerAssignable ? /* @__PURE__ */ jsx(Badge, { variant: "brand", children: t("customer_accounts.admin.roles.assignable", "Yes") }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: t("customer_accounts.admin.roles.notAssignable", "No") })
    }
  ], [t]);
  return /* @__PURE__ */ jsxs(Page, { children: [
    /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      DataTable,
      {
        title: t("customer_accounts.admin.roles.title", "Customer Roles"),
        actions: /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/customer_accounts/roles/create", children: t("customer_accounts.admin.roles.actions.create", "Create Role") }) }),
        columns,
        data: rows,
        searchValue: search,
        onSearchChange: (value) => {
          setSearch(value);
          setPage(1);
        },
        searchPlaceholder: t("customer_accounts.admin.roles.searchPlaceholder", "Search roles..."),
        perspective: { tableId: "customer_accounts.admin.roles" },
        emptyState: /* @__PURE__ */ jsx(
          ListEmptyState,
          {
            entityName: t("customer_accounts.admin.roles.title", "Customer Roles"),
            createHref: "/backend/customer_accounts/roles/create",
            createLabel: t("customer_accounts.admin.roles.actions.create", "Create Role")
          }
        ),
        onRowClick: (row) => router.push(`/backend/customer_accounts/roles/${row.id}`),
        rowActions: (row) => /* @__PURE__ */ jsx(
          RowActions,
          {
            items: [
              {
                id: "edit",
                label: t("customer_accounts.admin.roles.actions.edit", "Edit"),
                onSelect: () => {
                  router.push(`/backend/customer_accounts/roles/${row.id}`);
                }
              },
              ...!row.isDefault ? [{
                id: "delete",
                label: t("customer_accounts.admin.roles.actions.delete", "Delete"),
                destructive: true,
                onSelect: () => {
                  void handleDelete(row);
                }
              }] : []
            ]
          }
        ),
        pagination: { page, pageSize, total, totalPages, onPageChange: setPage },
        isLoading
      }
    ) }),
    ConfirmDialogElement
  ] });
}
export {
  CustomerRolesPage as default
};
//# sourceMappingURL=page.js.map
