"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 { DataTable } from "@open-mercato/ui/backend/DataTable";
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 { flash } from "@open-mercato/ui/backend/FlashMessages";
import { readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { mapOfferRow, renderOfferPriceSummary } from "./offerTableUtils.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("sales");
const PAGE_SIZE = 25;
const SAVE_CONTEXT_ID = "sales-channel-offers-panel";
function SalesChannelOffersPanel({ channelId, channelName }) {
  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.offers",
      retryLastMutation
    }),
    [retryLastMutation]
  );
  const [rows, setRows] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [total, setTotal] = React.useState(0);
  const [totalPages, setTotalPages] = React.useState(1);
  const [search, setSearch] = React.useState("");
  const [isLoading, setLoading] = React.useState(true);
  const [sorting, setSorting] = React.useState([]);
  const [reloadToken, setReloadToken] = React.useState(0);
  const columns = React.useMemo(() => [
    {
      accessorKey: "title",
      header: t("sales.channels.offers.table.offer", "Offer"),
      cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
        row.original.productMediaUrl ? /* @__PURE__ */ jsx(
          "img",
          {
            src: row.original.productMediaUrl,
            alt: row.original.productTitle ?? row.original.title,
            className: "h-12 w-12 rounded border object-cover"
          }
        ) : /* @__PURE__ */ jsx("div", { className: "h-12 w-12 rounded border bg-muted" }),
        /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-1", children: /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsx("span", { className: "font-medium", children: row.original.title }),
          /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: row.original.productTitle ?? t("sales.channels.offers.table.emptyProduct", "Unlinked product") })
        ] }) })
      ] }),
      meta: { sticky: true }
    },
    {
      accessorKey: "pricing",
      header: t("sales.channels.offers.table.pricing", "Prices"),
      cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: "text-sm", children: renderOfferPriceSummary(row.original, t) })
    },
    {
      accessorKey: "isActive",
      header: t("sales.channels.offers.table.active", "Active"),
      cell: ({ row }) => /* @__PURE__ */ jsx(BooleanIcon, { value: row.original.isActive })
    },
    {
      accessorKey: "updatedAt",
      header: t("sales.channels.offers.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 loadOffers = React.useCallback(async () => {
    if (!channelId) return;
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(page),
        pageSize: String(PAGE_SIZE),
        channelId
      });
      if (search.trim().length) {
        params.set("search", search.trim());
      }
      const sort = sorting[0];
      if (sort?.id) {
        params.set("sortField", sort.id);
        params.set("sortDir", sort.desc ? "desc" : "asc");
      }
      const payload = await readApiResultOrThrow(
        `/api/catalog/offers?${params.toString()}`,
        void 0,
        { errorMessage: t("sales.channels.offers.errors.load", "Failed to load offers.") }
      );
      const items = Array.isArray(payload.items) ? payload.items : [];
      setRows(items.map(mapOfferRow));
      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.offers", { err });
      flash(t("sales.channels.offers.errors.load", "Failed to load offers."), "error");
    } finally {
      setLoading(false);
    }
  }, [channelId, page, search, sorting, t]);
  React.useEffect(() => {
    void loadOffers();
  }, [loadOffers, reloadToken]);
  const handleDelete = React.useCallback(async (row) => {
    try {
      await runMutation({
        operation: () => withScopedApiRequestHeaders(
          buildOptimisticLockHeader(row.updatedAt),
          () => deleteCrud("catalog/offers", row.id, {
            errorMessage: t("sales.channels.offers.errors.delete", "Failed to delete offer.")
          })
        ),
        context: mutationContext,
        mutationPayload: { action: "delete", id: row.id }
      });
      flash(t("sales.channels.offers.messages.deleted", "Offer deleted."), "success");
      setReloadToken((token) => token + 1);
    } catch (err) {
      if (surfaceRecordConflict(err, t)) return;
      logger.error("sales.channels.offers.delete", { err });
      flash(t("sales.channels.offers.errors.delete", "Failed to delete offer."), "error");
    }
  }, [mutationContext, runMutation, t]);
  const handleSearchChange = React.useCallback((value) => {
    setSearch(value);
    setPage(1);
  }, []);
  const tableTitle = /* @__PURE__ */ jsxs("div", { children: [
    /* @__PURE__ */ jsx("div", { className: "text-lg font-semibold", children: t("sales.channels.offers.heading", "Offers for {{name}}", { name: channelName || t("sales.channels.nav.title", "Sales channels") }) }),
    /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("sales.channels.offers.subtitle", "Override product presentation and pricing per channel.") })
  ] });
  const actions = /* @__PURE__ */ jsx(Button, { asChild: true, children: /* @__PURE__ */ jsx(Link, { href: `/backend/sales/channels/${channelId}/offers/create`, children: t("sales.channels.offers.actions.create", "Add offer") }) });
  return /* @__PURE__ */ jsx(
    DataTable,
    {
      title: tableTitle,
      actions,
      columns,
      data: rows,
      isLoading,
      sorting,
      onSortingChange: setSorting,
      searchValue: search,
      onSearchChange: handleSearchChange,
      searchPlaceholder: t("sales.channels.offers.table.search", "Search offers\u2026"),
      pagination: {
        page,
        pageSize: PAGE_SIZE,
        total,
        totalPages,
        onPageChange: setPage
      },
      refreshButton: {
        label: t("sales.channels.offers.table.refresh", "Refresh"),
        onRefresh: () => setReloadToken((token) => token + 1),
        isRefreshing: isLoading
      },
      rowActions: (row) => /* @__PURE__ */ jsx(
        RowActions,
        {
          items: [
            {
              id: "edit",
              label: t("sales.channels.offers.actions.edit", "Edit"),
              href: `/backend/sales/channels/${channelId}/offers/${row.id}/edit`
            },
            {
              id: "delete",
              label: t("sales.channels.offers.actions.delete", "Delete"),
              onSelect: () => handleDelete(row),
              destructive: true
            }
          ]
        }
      ),
      onRowClick: (row) => router.push(`/backend/sales/channels/${channelId}/offers/${row.id}/edit`),
      emptyState: /* @__PURE__ */ jsx("div", { className: "py-10 text-center text-sm text-muted-foreground", children: t("sales.channels.offers.table.empty", "No offers for this channel yet.") })
    }
  );
}
export {
  SalesChannelOffersPanel
};
//# sourceMappingURL=SalesChannelOffersPanel.js.map
