import {
  AttributeValueInput
} from "./chunk-6PSJJHI4.js";
import {
  ChipInput
} from "./chunk-KDE4HKH2.js";
import "./chunk-VBRTC2VU.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteDrawer,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  require_dist
} from "./chunk-52KJSIHS.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
} 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/[attribute_id]/edit/index.tsx
import { Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";
import { useLinkQuery } from "@mercurjs/dashboard-shared";

// src/pages/products/[id]/attributes/[attribute_id]/edit/components/edit-attribute-form/edit-attribute-form.tsx
var import_types = __toESM(require_dist(), 1);
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, InlineTip, Input, Label, toast } from "@medusajs/ui";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var isVariantAxis = (attribute) => attribute.type === import_types.AttributeType.MULTI_SELECT || !!attribute.is_variant_axis;
var EditAttributeForm = ({
  productId,
  attribute
}) => {
  if (attribute.is_scoped) {
    return /* @__PURE__ */ jsx(EditScopedAttributeForm, { productId, attribute });
  }
  return /* @__PURE__ */ jsx(EditCatalogAttributeForm, { productId, attribute });
};
var AttributeWarning = () => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsx(
    InlineTip,
    {
      variant: "warning",
      label: t("products.create.attributes.warning"),
      children: t("products.create.attributes.editWarning")
    }
  );
};
var VariantAxisTip = () => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsx(InlineTip, { label: t("products.create.attributes.tip"), children: t("products.create.attributes.editVariantAxisTip") });
};
var EditScopedAttributeForm = ({
  productId,
  attribute
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const isAxis = isVariantAxis(attribute);
  const currentValues = attribute.values ?? attribute.all_values ?? [];
  const schema = zod.object({
    title: zod.string().trim().min(1, { message: t("products.create.attributes.errors.titleRequired") }),
    values: zod.union([zod.string(), zod.array(zod.string())]).refine(
      (v) => Array.isArray(v) ? v.length > 0 : v.trim().length > 0,
      { message: t("products.create.attributes.errors.valuesRequired") }
    )
  });
  const form = useForm({
    defaultValues: {
      title: attribute.name,
      values: isAxis ? currentValues.map((v) => v.name) : currentValues[0]?.name ?? ""
    },
    resolver: zodResolver(schema)
  });
  const { mutateAsync, isPending } = useBatchProductAttributes(productId);
  const handleSubmit = form.handleSubmit(async (data) => {
    const title = data.title.trim() !== attribute.name ? data.title.trim() : void 0;
    let payload;
    if (isAxis) {
      const newNames = (Array.isArray(data.values) ? data.values : []).map((v) => v.trim()).filter(Boolean);
      const byName = new Map(currentValues.map((v) => [v.name, v.id]));
      const add = newNames.filter((name) => !byName.has(name)).map((value) => ({ value }));
      const remove = currentValues.filter((v) => !newNames.includes(v.name)).map((v) => v.id);
      payload = {
        update: [{ id: attribute.id, title, add, remove }]
      };
    } else {
      const value = Array.isArray(data.values) ? data.values[0] ?? "" : data.values;
      payload = {
        update: [{ id: attribute.id, title, value }]
      };
    }
    await mutateAsync(payload, {
      onSuccess: () => handleSuccess(),
      onError: (error) => toast.error(error.message)
    });
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
    /* @__PURE__ */ jsx(RouteDrawer.Body, { children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
      /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-component shadow-elevation-card-rest rounded-xl p-1.5", children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[min-content,1fr] items-start 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(
          Form.Field,
          {
            control: form.control,
            name: "title",
            render: ({ field, fieldState }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
              /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                Input,
                {
                  ...field,
                  "aria-invalid": fieldState.invalid ? "true" : void 0,
                  className: fieldState.invalid ? "bg-ui-bg-field-component shadow-borders-error focus:shadow-borders-error" : "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover",
                  "data-testid": "edit-attribute-title-input"
                }
              ) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, {})
            ] })
          }
        ),
        /* @__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: "values",
            render: ({ field: { onChange, value }, fieldState }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
              /* @__PURE__ */ jsx(Form.Control, { children: isAxis ? /* @__PURE__ */ jsx(
                ChipInput,
                {
                  variant: "contrast",
                  value: Array.isArray(value) ? value : [],
                  onChange,
                  "aria-invalid": fieldState.invalid ? "true" : void 0,
                  className: fieldState.invalid ? "shadow-borders-error focus-within:!shadow-borders-error" : void 0,
                  placeholder: t(
                    "products.create.attributes.valuePlaceholder"
                  )
                }
              ) : /* @__PURE__ */ jsx(
                AttributeValueInput,
                {
                  type: attribute.type,
                  value,
                  onChange,
                  placeholder: t(
                    "products.create.attributes.valuePlaceholder"
                  )
                }
              ) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, {})
            ] })
          }
        )
      ] }) }),
      isAxis && /* @__PURE__ */ jsx(VariantAxisTip, {}),
      /* @__PURE__ */ jsx(AttributeWarning, {})
    ] }) }),
    /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(
        Button,
        {
          size: "small",
          type: "submit",
          isLoading: isPending,
          "data-testid": "edit-attribute-submit-button",
          children: t("actions.save")
        }
      )
    ] }) })
  ] }) });
};
var EditCatalogAttributeForm = ({
  productId,
  attribute
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { feature_flags } = useFeatureFlags();
  const isProductRequestEnabled = !!feature_flags?.[import_types.MercurFeatureFlags.PRODUCT_REQUEST];
  const isAxis = isVariantAxis(attribute);
  const hasPresetValues = attribute.type === import_types.AttributeType.SINGLE_SELECT || attribute.type === import_types.AttributeType.MULTI_SELECT;
  const labelTooltip = attribute.description || (attribute.is_required ? t("products.create.attributes.requiredTooltip") : void 0);
  const initialValues = (() => {
    const selected = attribute.values ?? [];
    if (attribute.type === import_types.AttributeType.MULTI_SELECT) {
      return selected.map((v) => v.name);
    }
    return selected[0]?.name ?? "";
  })();
  const schema = zod.object({
    values: zod.union([zod.string(), zod.array(zod.string())]).refine(
      (v) => Array.isArray(v) ? v.length > 0 : v.trim().length > 0,
      { message: t("products.create.attributes.errors.valuesRequired") }
    )
  });
  const form = useForm({
    defaultValues: { values: initialValues },
    resolver: zodResolver(schema)
  });
  const { mutateAsync, isPending } = useBatchProductAttributes(productId);
  const handleSubmit = form.handleSubmit(async (data) => {
    const vals = Array.isArray(data.values) ? data.values : [data.values].filter((s) => s.trim().length > 0);
    let payload;
    if (hasPresetValues) {
      const selectedIds = (attribute.all_values ?? []).filter((v) => vals.includes(v.name)).map((v) => v.id);
      if (attribute.is_variant_axis) {
        const currentIds = (attribute.values ?? []).map((v) => v.id);
        const add = selectedIds.filter((id) => !currentIds.includes(id));
        const remove = currentIds.filter((id) => !selectedIds.includes(id));
        payload = { update: [{ id: attribute.id, add, remove }] };
      } else {
        payload = {
          remove: [attribute.id],
          add: [{ id: attribute.id, value_ids: selectedIds }]
        };
      }
    } else {
      payload = {
        update: [
          {
            id: attribute.id,
            value: attribute.type === import_types.AttributeType.TOGGLE ? vals[0] === "true" : vals[0]
          }
        ]
      };
    }
    await mutateAsync(payload, {
      onSuccess: () => {
        handleSuccess();
        toast.success(
          isProductRequestEnabled ? t("products.edit.requestSuccessToast") : t("products.edit.attributes.updateSuccessToast")
        );
      },
      onError: (error) => toast.error(error.message)
    });
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
    /* @__PURE__ */ jsx(RouteDrawer.Body, { children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "values",
          render: ({ field: { onChange, value } }) => /* @__PURE__ */ jsxs(Form.Item, { children: [
            /* @__PURE__ */ jsx(Form.Label, { tooltip: labelTooltip, children: attribute.name }),
            /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
              AttributeValueInput,
              {
                type: attribute.type,
                value,
                onChange,
                availableValues: attribute.all_values ?? []
              }
            ) }),
            /* @__PURE__ */ jsx(Form.ErrorMessage, {}),
            isAxis && /* @__PURE__ */ jsx(VariantAxisTip, {})
          ] })
        }
      ),
      /* @__PURE__ */ jsx(AttributeWarning, {})
    ] }) }),
    /* @__PURE__ */ jsx(RouteDrawer.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
      /* @__PURE__ */ jsx(RouteDrawer.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(
        Button,
        {
          size: "small",
          type: "submit",
          isLoading: isPending,
          "data-testid": "edit-attribute-submit-button",
          children: t("actions.save")
        }
      )
    ] }) })
  ] }) });
};

// src/pages/products/[id]/attributes/[attribute_id]/edit/index.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var Component = () => {
  const { id, attribute_id } = useParams();
  const { t } = useTranslation2();
  const query = useLinkQuery("product", PRODUCT_DETAIL_QUERY.fields);
  const { product, isLoading, isError, error } = useProduct(id, query);
  if (isError) {
    throw error;
  }
  const attribute = product?.attributes?.find(
    (a) => a.id === attribute_id
  );
  const ready = !isLoading && !!product && !!attribute;
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsxs2(RouteDrawer.Header, { children: [
      /* @__PURE__ */ jsx2(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx2(Heading, { children: t("products.editAttribute") }) }),
      /* @__PURE__ */ jsx2(RouteDrawer.Description, { className: "sr-only", children: t("products.editAttributeHint") })
    ] }),
    ready && /* @__PURE__ */ jsx2(EditAttributeForm, { productId: id, attribute })
  ] });
};
export {
  Component
};
