"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { TagsInput } from "@open-mercato/ui/backend/inputs/TagsInput";
import { Label } from "@open-mercato/ui/primitives/label";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
const formatCategoryLabel = (name, fallback, parentName) => {
  const base = typeof name === "string" && name.trim().length ? name.trim() : fallback;
  const parent = typeof parentName === "string" && parentName.trim().length ? parentName.trim() : null;
  return parent ? `${base} / ${parent}` : base;
};
function ProductCategorizeSection({
  values,
  setValue,
  errors,
  initialCategoryOptions,
  initialChannelOptions,
  initialTagOptions
}) {
  const t = useT();
  const [categoryOptionsMap, setCategoryOptionsMap] = React.useState({});
  const [channelOptionsMap, setChannelOptionsMap] = React.useState({});
  const [tagOptionsMap, setTagOptionsMap] = React.useState({});
  const registerPickerOptions = React.useCallback(
    (setter, options) => {
      setter((prev) => {
        const next = { ...prev };
        options.forEach((option) => {
          if (option.value) next[option.value] = option;
        });
        return next;
      });
    },
    []
  );
  const categorySuggestions = React.useMemo(() => Object.values(categoryOptionsMap), [categoryOptionsMap]);
  const channelSuggestions = React.useMemo(() => Object.values(channelOptionsMap), [channelOptionsMap]);
  const tagSuggestions = React.useMemo(() => Object.values(tagOptionsMap), [tagOptionsMap]);
  React.useEffect(() => {
    if (initialCategoryOptions?.length) {
      registerPickerOptions(setCategoryOptionsMap, initialCategoryOptions);
    }
  }, [initialCategoryOptions, registerPickerOptions]);
  React.useEffect(() => {
    if (initialChannelOptions?.length) {
      registerPickerOptions(setChannelOptionsMap, initialChannelOptions);
    }
  }, [initialChannelOptions, registerPickerOptions]);
  React.useEffect(() => {
    if (initialTagOptions?.length) {
      registerPickerOptions(setTagOptionsMap, initialTagOptions);
    }
  }, [initialTagOptions, registerPickerOptions]);
  const resolveCategoryLabel = React.useCallback(
    (id) => categoryOptionsMap[id]?.label ?? id,
    [categoryOptionsMap]
  );
  const resolveCategoryDescription = React.useCallback(
    (id) => categoryOptionsMap[id]?.description ?? null,
    [categoryOptionsMap]
  );
  const resolveChannelLabel = React.useCallback(
    (id) => channelOptionsMap[id]?.label ?? id,
    [channelOptionsMap]
  );
  const resolveChannelDescription = React.useCallback(
    (id) => channelOptionsMap[id]?.description ?? null,
    [channelOptionsMap]
  );
  const resolveTagLabel = React.useCallback((id) => tagOptionsMap[id]?.label ?? id, [tagOptionsMap]);
  const loadCategorySuggestions = React.useCallback(
    async (term) => {
      try {
        const params = new URLSearchParams({ pageSize: "200", view: "manage" });
        if (term && term.trim().length) params.set("search", term.trim());
        const payload = await readApiResultOrThrow(
          `/api/catalog/categories?${params.toString()}`,
          void 0,
          { errorMessage: t("catalog.products.filters.categoriesLoadError", "Failed to load categories") }
        );
        const items = Array.isArray(payload?.items) ? payload.items : [];
        const options = items.map((entry) => {
          const value = typeof entry.id === "string" ? entry.id : null;
          if (!value) return null;
          const parentName = typeof entry.parentName === "string" && entry.parentName.trim().length ? entry.parentName : null;
          const label = formatCategoryLabel(
            typeof entry.name === "string" ? entry.name : null,
            value,
            parentName
          );
          const description = parentName && !label.toLowerCase().includes(parentName.toLowerCase()) ? parentName : null;
          return { value, label, description };
        }).filter(
          (option) => !!option
        );
        registerPickerOptions(setCategoryOptionsMap, options);
        return options;
      } catch {
        return [];
      }
    },
    [registerPickerOptions, t]
  );
  const loadChannelSuggestions = React.useCallback(
    async (term) => {
      try {
        const params = new URLSearchParams({ pageSize: "100", isActive: "true" });
        if (term && term.trim().length) params.set("search", term.trim());
        const payload = await readApiResultOrThrow(
          `/api/sales/channels?${params.toString()}`,
          void 0,
          { errorMessage: t("catalog.products.filters.channelsLoadError", "Failed to load channels") }
        );
        const items = Array.isArray(payload?.items) ? payload.items : [];
        const options = items.map((entry) => {
          const value = typeof entry.id === "string" ? entry.id : null;
          if (!value) return null;
          const label = typeof entry.name === "string" && entry.name.trim().length ? entry.name : typeof entry.code === "string" && entry.code.trim().length ? entry.code : value;
          const description = typeof entry.code === "string" && entry.code.trim().length ? entry.code : null;
          return { value, label, description };
        }).filter(
          (option) => !!option
        );
        registerPickerOptions(setChannelOptionsMap, options);
        return options;
      } catch {
        return [];
      }
    },
    [registerPickerOptions, t]
  );
  const loadTagSuggestions = React.useCallback(
    async (term) => {
      try {
        const params = new URLSearchParams({ pageSize: "100" });
        if (term && term.trim().length) params.set("search", term.trim());
        const payload = await readApiResultOrThrow(
          `/api/catalog/tags?${params.toString()}`,
          void 0,
          { errorMessage: t("catalog.products.filters.tagsLoadError", "Failed to load tags") }
        );
        const items = Array.isArray(payload?.items) ? payload.items : [];
        const options = items.map((entry) => {
          const rawLabel = typeof entry.label === "string" ? entry.label.trim() : "";
          if (!rawLabel) return null;
          return { value: rawLabel, label: rawLabel };
        }).filter(
          (option) => !!option
        );
        registerPickerOptions(setTagOptionsMap, options);
        return options;
      } catch {
        return [];
      }
    },
    [registerPickerOptions, t]
  );
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { children: t("catalog.products.create.organize.categoriesLabel", "Categories") }),
      /* @__PURE__ */ jsx(
        TagsInput,
        {
          value: Array.isArray(values.categoryIds) ? values.categoryIds : [],
          onChange: (next) => setValue("categoryIds", next),
          suggestions: categorySuggestions,
          loadSuggestions: loadCategorySuggestions,
          allowCustomValues: false,
          resolveLabel: resolveCategoryLabel,
          resolveDescription: resolveCategoryDescription,
          placeholder: t("catalog.products.create.organize.categoriesPlaceholder", "Search categories")
        }
      ),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.products.create.organize.categoriesHelp", "Assign products to one or more taxonomy nodes.") }),
      errors.categoryIds ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.categoryIds }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { children: t("catalog.products.create.organize.channelsLabel", "Sales channels") }),
      /* @__PURE__ */ jsx(
        TagsInput,
        {
          value: Array.isArray(values.channelIds) ? values.channelIds : [],
          onChange: (next) => setValue("channelIds", next),
          suggestions: channelSuggestions,
          loadSuggestions: loadChannelSuggestions,
          allowCustomValues: false,
          resolveLabel: resolveChannelLabel,
          resolveDescription: resolveChannelDescription,
          placeholder: t("catalog.products.create.organize.channelsPlaceholder", "Pick channels")
        }
      ),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.products.create.organize.channelsHelp", "Selected channels will receive default offers for this product.") }),
      errors.channelIds ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.channelIds }) : null
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { children: t("catalog.products.create.organize.tagsLabel", "Tags") }),
      /* @__PURE__ */ jsx(
        TagsInput,
        {
          value: Array.isArray(values.tags) ? values.tags : [],
          onChange: (next) => setValue("tags", next),
          suggestions: tagSuggestions,
          loadSuggestions: loadTagSuggestions,
          resolveLabel: resolveTagLabel,
          placeholder: t("catalog.products.create.organize.tagsPlaceholder", "Add tag and press Enter")
        }
      ),
      /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.products.create.organize.tagsHelp", "Describe products with shared labels to build quick filters.") }),
      errors.tags ? /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: errors.tags }) : null
    ] })
  ] });
}
export {
  ProductCategorizeSection
};
//# sourceMappingURL=ProductCategorizeSection.js.map
