"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { DataTable, withDataTableNamespaces } from "@open-mercato/ui/backend/DataTable";
import { Button } from "@open-mercato/ui/primitives/button";
import { RowActions } from "@open-mercato/ui/backend/RowActions";
import { BooleanIcon } from "@open-mercato/ui/backend/ValueIcons";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { buildOptimisticLockHeader, extractOptimisticLockConflict } from "@open-mercato/ui/backend/utils/optimisticLock";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const PAGE_SIZE = 25;
const SAVE_CONTEXT_ID = "sales-channels-list";
function SalesChannelsPage() {
  const t = useT();
  const router = useRouter();
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: SAVE_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const mutationContext = React.useMemo(
    () => ({
      formId: SAVE_CONTEXT_ID,
      resourceKind: "sales.channels",
      retryLastMutation
    }),
    [retryLastMutation]
  );
  const scopeVersion = useOrganizationScopeVersion();
  const [rows, setRows] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const [sorting, setSorting] = React.useState([]);
  const [search, setSearch] = React.useState("");
  const [isLoading, setLoading] = React.useState(true);
  const [reloadToken, setReloadToken] = React.useState(0);
  const columns = React.useMemo(() => [
    {
      accessorKey: "name",
      header: t("sales.channels.table.name", "Name"),
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsx("span", { className: "font-medium", children: row.original.name }),
        row.original.description ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: row.original.description }) : null
      ] }),
      meta: { sticky: true }
    },
    {
      accessorKey: "code",
      header: t("sales.channels.table.code", "Code"),
      cell: ({ row }) => row.original.code ? /* @__PURE__ */ jsx("span", { className: "font-mono text-xs", children: row.original.code }) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "\u2014" })
    },
    {
      accessorKey: "offerCount",
      header: t("sales.channels.table.offers", "Product offers"),
      cell: ({ row }) => /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: row.original.offerCount })
    },
    {
      accessorKey: "isActive",
      header: t("sales.channels.table.active", "Active"),
      cell: ({ row }) => /* @__PURE__ */ jsx(BooleanIcon, { value: row.original.isActive })
    },
    {
      accessorKey: "updatedAt",
      header: t("sales.channels.table.updated", "Updated"),
      cell: ({ row }) => row.original.updatedAt ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: new Date(row.original.updatedAt).toLocaleDateString() }) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "\u2014" })
    }
  ], [t]);
  const loadChannels = React.useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(page),
        pageSize: String(PAGE_SIZE)
      });
      const sort = sorting[0];
      if (sort?.id) {
        params.set("sortField", sort.id);
        params.set("sortDir", sort.desc ? "desc" : "asc");
      }
      if (search.trim().length) {
        params.set("search", search.trim());
      }
      const payload = await readApiResultOrThrow(
        `/api/sales/channels?${params.toString()}`,
        void 0,
        { errorMessage: t("sales.channels.table.errors.load", "Failed to load channels.") }
      );
      const items = Array.isArray(payload.items) ? payload.items : [];
      setRows(items.map(mapApiChannel));
      setTotal(typeof payload.total === "number" ? payload.total : items.length);
      setTotalPages(typeof payload.totalPages === "number" ? payload.totalPages : Math.max(1, Math.ceil(items.length / PAGE_SIZE)));
    } catch (err) {
      logger.error("sales.channels.list", { err });
      flash(t("sales.channels.table.errors.load", "Failed to load channels."), "error");
    } finally {
      setLoading(false);
    }
  }, [page, search, sorting, t]);
  React.useEffect(() => {
    void loadChannels();
  }, [loadChannels, scopeVersion, reloadToken]);
  const handleSearchChange = React.useCallback((value) => {
    setSearch(value);
    setPage(1);
  }, []);
  const handleRefresh = React.useCallback(() => {
    setReloadToken((token) => token + 1);
  }, []);
  const handleDelete = React.useCallback(async (row) => {
    try {
      await runMutation({
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(row.updatedAt),
          () => deleteCrud("sales/channels", row.id, {
            errorMessage: t("sales.channels.table.errors.delete", "Failed to delete channel.")
          })
        ),
        context: mutationContext,
        mutationPayload: { action: "delete", id: row.id }
      });
      flash(t("sales.channels.table.messages.deleted", "Channel deleted."), "success");
      handleRefresh();
    } catch (err) {
      if (extractOptimisticLockConflict(err)) {
        flash(
          t("ui.forms.flash.recordModified", "This record was modified by someone else. Refresh and try again."),
          "error"
        );
        handleRefresh();
        return;
      }
      logger.error("sales.channels.delete", { err });
    }
  }, [handleRefresh, mutationContext, runMutation, t]);
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    DataTable,
    {
      title: /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
        /* @__PURE__ */ jsx("span", { children: t("sales.channels.nav.title", "Sales channels") }),
        /* @__PURE__ */ jsx("span", { className: "text-sm font-normal text-muted-foreground", children: t("sales.channels.table.subtitle", "Organize catalog offers per marketplace or storefront.") })
      ] }),
      actions: /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: "/backend/sales/channels/create", children: t("sales.channels.actions.create", "Add channel") }) }),
      columns,
      data: rows,
      sorting,
      onSortingChange: setSorting,
      isLoading,
      searchValue: search,
      onSearchChange: handleSearchChange,
      searchPlaceholder: t("sales.channels.table.search", "Search channels\u2026"),
      pagination: {
        page,
        pageSize: PAGE_SIZE,
        total,
        totalPages,
        onPageChange: setPage
      },
      refreshButton: {
        label: t("sales.channels.table.refresh", "Refresh"),
        onRefresh: handleRefresh,
        isRefreshing: isLoading
      },
      rowActions: (row) => /* @__PURE__ */ jsx(
        RowActions,
        {
          items: [
            {
              id: "edit",
              label: t("sales.channels.table.actions.edit", "Edit"),
              href: `/backend/sales/channels/${row.id}/edit`
            },
            {
              id: "delete",
              label: t("sales.channels.table.actions.delete", "Delete"),
              onSelect: () => handleDelete(row)
            }
          ]
        }
      ),
      onRowClick: (row) => router.push(`/backend/sales/channels/${row.id}/edit`),
      emptyState: /* @__PURE__ */ jsx("div", { className: "py-10 text-center text-sm text-muted-foreground", children: t("sales.channels.table.empty", "No channels yet.") })
    }
  ) }) });
}
function mapApiChannel(item) {
  const id = typeof item.id === "string" ? item.id : "";
  return withDataTableNamespaces({
    id,
    name: typeof item.name === "string" ? item.name : id,
    code: typeof item.code === "string" && item.code.length ? item.code : null,
    description: typeof item.description === "string" && item.description.length ? item.description : null,
    offerCount: typeof item.offerCount === "number" ? item.offerCount : typeof item.offer_count === "number" ? item.offer_count : 0,
    isActive: item.isActive === true || item.is_active === true,
    updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : typeof item.updated_at === "string" ? item.updated_at : null
  }, item);
}
export {
  SalesChannelsPage as default
};
//# sourceMappingURL=page.js.map
