import {
  AttributeValueInput
} from "./chunk-6PSJJHI4.js";
import "./chunk-432S4FGR.js";
import {
  DataTable
} from "./chunk-IV57G2CB.js";
import {
  useAttributeTableFilters,
  useAttributeTableQuery
} from "./chunk-4OQLPIUZ.js";
import "./chunk-NWU7EGGF.js";
import "./chunk-VBRTC2VU.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import {
  require_dist
} from "./chunk-52KJSIHS.js";
import "./chunk-BDGZ4EQO.js";
import "./chunk-LAVHRER2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import {
  useFeatureFlags
} from "./chunk-RLRWDHME.js";
import "./chunk-K5324KIX.js";
import "./chunk-FV76G2D7.js";
import "./chunk-GHDLST2P.js";
import "./chunk-YVYYOBAE.js";
import "./chunk-L2NJPDUD.js";
import "./chunk-P7UBW2EI.js";
import "./chunk-MR6REQKT.js";
import "./chunk-EPSDO2MJ.js";
import "./chunk-BHEU34FL.js";
import "./chunk-W34KDYZA.js";
import "./chunk-II3CLUXA.js";
import "./chunk-XKEYHWBS.js";
import "./chunk-J2XUEO2E.js";
import "./chunk-656G74I2.js";
import "./chunk-VWPNMEOE.js";
import "./chunk-O72AIZUN.js";
import "./chunk-VUWAOX7H.js";
import "./chunk-5DKUSZQ7.js";
import "./chunk-DIAWPVYS.js";
import "./chunk-4U2BLH45.js";
import {
  PRODUCT_DETAIL_QUERY
} from "./chunk-Q6SPIHFR.js";
import {
  useBatchProductAttributes,
  useProduct,
  useProductAttributes
} from "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import {
  __toESM
} from "./chunk-NBMM2TZK.js";

// src/pages/products/[id]/attributes/add/index.tsx
var import_types = __toESM(require_dist(), 1);
import { XMarkMini } from "@medusajs/icons";
import {
  Badge,
  Button,
  createDataTableColumnHelper,
  Heading,
  IconButton,
  InlineTip,
  Input,
  Label,
  Text,
  toast
} from "@medusajs/ui";
import { useEffect, useMemo, useState } from "react";
import { useFieldArray, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { keepPreviousData } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import i18n from "i18next";
import * as zod from "zod";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 20;
var PREFIX = "add-existing-attrs";
var MAX_VISIBLE_VALUES = 2;
var ATTRIBUTE_TYPE_LABELS = {
  single_select: "attributes.type.select",
  multi_select: "attributes.type.multivalue",
  unit: "attributes.type.unit",
  toggle: "attributes.type.toggle",
  text: "attributes.type.text_area"
};
var AttributeValueSchema = zod.object({
  attribute_id: zod.string(),
  name: zod.string(),
  type: zod.string(),
  is_variant_axis: zod.boolean(),
  available_values: zod.array(
    zod.object({ id: zod.string(), name: zod.string() })
  ),
  values: zod.union([zod.string(), zod.array(zod.string())]).refine(
    (val) => {
      if (Array.isArray(val)) return val.length > 0;
      return val.length > 0;
    },
    { message: i18n.t("validation.valueRequired") }
  )
});
var AddExistingAttributesSchema = zod.object({
  attributes: zod.array(AttributeValueSchema)
});
var Component = () => {
  const { id: productId } = useParams();
  return /* @__PURE__ */ jsxs(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
    /* @__PURE__ */ jsx(Content, { productId })
  ] });
};
var Content = ({ productId }) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { feature_flags } = useFeatureFlags();
  const isProductRequestEnabled = !!feature_flags?.[import_types.MercurFeatureFlags.PRODUCT_REQUEST];
  const [step, setStep] = useState("select");
  const [rowSelection, setRowSelection] = useState({});
  const { searchParams } = useAttributeTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { product_attributes, count, isLoading, isError, error } = useProductAttributes(searchParams, {
    placeholderData: keepPreviousData
  });
  const { product } = useProduct(productId, PRODUCT_DETAIL_QUERY);
  const assignedIds = useMemo(
    () => new Set(
      (product?.attributes ?? []).map(
        (a) => a.id
      )
    ),
    [product]
  );
  const lockedIds = useMemo(() => {
    const ids = new Set(assignedIds);
    for (const attr of product_attributes ?? []) {
      if (attr.is_required) ids.add(attr.id);
    }
    return ids;
  }, [assignedIds, product_attributes]);
  useEffect(() => {
    if (!lockedIds.size) return;
    setRowSelection((prev) => {
      const next = { ...prev };
      let changed = false;
      for (const id of lockedIds) {
        if (!next[id]) {
          next[id] = true;
          changed = true;
        }
      }
      return changed ? next : prev;
    });
  }, [lockedIds]);
  const { mutateAsync, isPending } = useBatchProductAttributes(productId);
  const form = useForm({
    defaultValues: { attributes: [] },
    resolver: zodResolver(AddExistingAttributesSchema)
  });
  const { fields, remove } = useFieldArray({
    control: form.control,
    name: "attributes"
  });
  const filters = useAttributeTableFilters();
  const columns = useColumns();
  if (isError) {
    throw error;
  }
  const handleContinue = () => {
    const selectedIds = Object.keys(rowSelection).filter(
      (id) => rowSelection[id] && !lockedIds.has(id)
    );
    if (!selectedIds.length) return;
    const attrs = selectedIds.map(
      (id) => product_attributes?.find((a) => a.id === id)
    ).filter(Boolean).map((attr) => ({
      attribute_id: attr.id,
      name: attr.name,
      type: attr.type,
      is_variant_axis: attr.is_variant_axis,
      available_values: attr.values?.map((v) => ({
        id: v.id,
        name: v.name
      })) ?? [],
      values: attr.type === import_types.AttributeType.MULTI_SELECT ? [] : ""
    }));
    form.reset({ attributes: attrs });
    setStep("values");
  };
  const handleBack = () => {
    setStep("select");
  };
  const handleRemoveAttr = (index, attrId) => {
    remove(index);
    setRowSelection((prev) => {
      const next = { ...prev };
      delete next[attrId];
      return next;
    });
  };
  const handleSubmit = form.handleSubmit(async (data) => {
    const add = [];
    for (const attr of data.attributes) {
      const vals = Array.isArray(attr.values) ? attr.values : attr.values ? [attr.values] : [];
      const hasPresetValues = attr.type === "single_select" || attr.type === "multi_select";
      if (hasPresetValues) {
        const nameToId = new Map(
          attr.available_values.map((v) => [v.name, v.id])
        );
        const valueIds = vals.map((name) => nameToId.get(name)).filter(Boolean);
        if (!valueIds.length) continue;
        add.push({ id: attr.attribute_id, value_ids: valueIds });
      } else {
        if (!vals.length || !vals[0]) continue;
        add.push({
          id: attr.attribute_id,
          value: attr.type === "toggle" ? vals[0] === "true" : vals[0]
        });
      }
    }
    if (!add.length) {
      handleSuccess();
      return;
    }
    await mutateAsync(
      { add },
      {
        onSuccess: () => {
          handleSuccess();
          toast.success(
            isProductRequestEnabled ? t("products.edit.requestSuccessToast") : t("products.edit.attributes.addSuccessToast")
          );
        },
        onError: (err) => {
          toast.error(err.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(Fragment, { children: step === "select" ? /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(
      DataTable,
      {
        data: product_attributes,
        columns,
        filters,
        rowCount: count,
        pageSize: PAGE_SIZE,
        getRowId: (row) => row.id,
        rowSelection: {
          state: rowSelection,
          onRowSelectionChange: setRowSelection,
          enableRowSelection: (row) => !lockedIds.has(row.original.id)
        },
        isLoading,
        layout: "fill",
        prefix: PREFIX
      }
    ) }),
    /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", type: "button", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(
        Button,
        {
          size: "small",
          type: "button",
          onClick: handleContinue,
          disabled: !Object.entries(rowSelection).some(
            ([id, selected]) => selected && !lockedIds.has(id)
          ),
          children: t("actions.continue")
        }
      )
    ] }) })
  ] }) : /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex-1 overflow-auto", children: /* @__PURE__ */ jsxs("div", { className: "mx-auto flex w-full max-w-[720px] flex-col gap-y-8 p-16", children: [
          /* @__PURE__ */ jsxs("div", { children: [
            /* @__PURE__ */ jsx(Heading, { level: "h2", children: t("products.create.attributes.header") }),
            /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle mt-1", children: t("products.create.attributes.description") })
          ] }),
          /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-4", children: fields.map((field, index) => /* @__PURE__ */ jsxs(
            "div",
            {
              className: "bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-start gap-1.5 rounded-xl p-1.5",
              children: [
                /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[min-content,1fr] items-center gap-1.5", children: [
                  /* @__PURE__ */ jsx("div", { className: "flex items-center px-2 py-1.5", children: /* @__PURE__ */ jsx(
                    Label,
                    {
                      size: "xsmall",
                      weight: "plus",
                      className: "text-ui-fg-subtle",
                      children: t("fields.title")
                    }
                  ) }),
                  /* @__PURE__ */ jsx(
                    Input,
                    {
                      value: field.name,
                      disabled: true,
                      className: "bg-ui-bg-field-component"
                    }
                  ),
                  /* @__PURE__ */ jsx("div", { className: "flex items-center px-2 py-1.5", children: /* @__PURE__ */ jsx(
                    Label,
                    {
                      size: "xsmall",
                      weight: "plus",
                      className: "text-ui-fg-subtle",
                      children: t("fields.values")
                    }
                  ) }),
                  /* @__PURE__ */ jsx(
                    Form.Field,
                    {
                      control: form.control,
                      name: `attributes.${index}.values`,
                      render: ({ field: { onChange, value } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
                        /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                          AttributeValueInput,
                          {
                            type: field.type,
                            value,
                            onChange,
                            availableValues: field.available_values
                          }
                        ) }),
                        /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                      ] })
                    }
                  ),
                  field.is_variant_axis && /* @__PURE__ */ jsxs(Fragment, { children: [
                    /* @__PURE__ */ jsx("div", {}),
                    /* @__PURE__ */ jsx(
                      InlineTip,
                      {
                        label: t("products.create.attributes.tip"),
                        children: t(
                          "products.create.attributes.variantAxisTip"
                        )
                      }
                    )
                  ] })
                ] }),
                /* @__PURE__ */ jsx(
                  IconButton,
                  {
                    type: "button",
                    size: "small",
                    variant: "transparent",
                    className: "text-ui-fg-muted",
                    onClick: () => handleRemoveAttr(index, field.attribute_id),
                    children: /* @__PURE__ */ jsx(XMarkMini, {})
                  }
                )
              ]
            },
            field.id
          )) })
        ] }) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              variant: "secondary",
              type: "button",
              onClick: handleBack,
              children: t("actions.back")
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              size: "small",
              type: "submit",
              isLoading: isPending,
              disabled: !fields.length,
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) }) });
};
var columnHelper = createDataTableColumnHelper();
var useColumns = () => {
  const { t } = useTranslation();
  return useMemo(
    () => [
      columnHelper.select(),
      columnHelper.accessor("name", {
        header: t("attributes.fields.name"),
        enableSorting: false
      }),
      columnHelper.accessor("type", {
        header: t("attributes.fields.type"),
        cell: (info) => {
          const type = info.getValue();
          const labelKey = ATTRIBUTE_TYPE_LABELS[type];
          return labelKey ? t(labelKey) : type;
        },
        enableSorting: false
      }),
      columnHelper.accessor("is_variant_axis", {
        header: t("attributes.fields.variantAxis"),
        cell: (info) => info.getValue() ? t("filters.radio.yes") : t("filters.radio.no"),
        enableSorting: false
      }),
      columnHelper.display({
        id: "values",
        header: t("attributes.fields.values"),
        cell: ({ row }) => {
          const values = row.original.type === "toggle" ? [] : row.original.values ?? [];
          if (!values.length) {
            return /* @__PURE__ */ jsx("span", { className: "text-ui-fg-muted", children: "-" });
          }
          const visible = values.slice(0, MAX_VISIBLE_VALUES);
          const remaining = values.length - MAX_VISIBLE_VALUES;
          return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-1", children: [
            visible.map((v) => /* @__PURE__ */ jsx(Badge, { size: "2xsmall", color: "grey", children: v.name }, v.id)),
            remaining > 0 && /* @__PURE__ */ jsxs(Badge, { size: "2xsmall", color: "grey", children: [
              "+",
              remaining
            ] })
          ] });
        }
      })
    ],
    [t]
  );
};
export {
  Component
};
