import {
  transformNullableFormData,
  transformNullableFormNumber
} from "./chunk-7RPRNVBS.js";
import "./chunk-NXDFDEKP.js";
import {
  CountrySelect
} from "./chunk-7CAFYKKA.js";
import {
  AttributeValueInput
} from "./chunk-6PSJJHI4.js";
import "./chunk-JRTZWK77.js";
import {
  optionalInt
} from "./chunk-AJLGY3LQ.js";
import "./chunk-SMQT3ZNO.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 {
  useProduct,
  useProductVariant,
  useUpdateProductVariant,
  variantsQueryKeys
} from "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import {
  queryClient
} from "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import {
  sdk
} from "./chunk-DTGEFKK4.js";
import {
  __toESM
} from "./chunk-NBMM2TZK.js";

// src/pages/product-variants/product-variant-edit/product-variant-edit.tsx
import { Heading as Heading2 } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { useLoaderData, useParams, useSearchParams } from "react-router-dom";

// src/pages/product-variants/product-variant-edit/components/product-edit-variant-form/product-edit-variant-form.tsx
var import_types = __toESM(require_dist(), 1);
import { zodResolver } from "@hookform/resolvers/zod";
import { InformationCircleSolid } from "@medusajs/icons";
import { Button, Divider, Heading, Input, Tooltip, toast } from "@medusajs/ui";
import i18next from "i18next";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var ProductEditVariantSchema = z.object({
  title: z.string().min(1, i18next.t("products.variant.validation.titleRequired")),
  sku: z.string().optional(),
  ean: z.string().optional(),
  upc: z.string().optional(),
  barcode: z.string().optional(),
  weight: optionalInt,
  height: optionalInt,
  width: optionalInt,
  length: optionalInt,
  mid_code: z.string().optional(),
  hs_code: z.string().optional(),
  origin_country: z.string().optional(),
  options: z.record(z.string().min(1, i18next.t("products.variant.validation.optionRequired"))).optional()
});
var ProductEditVariantForm = ({
  variant,
  product
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { feature_flags } = useFeatureFlags();
  const isProductRequestEnabled = !!feature_flags?.[import_types.MercurFeatureFlags.PRODUCT_REQUEST];
  const variantAttributes = product.attributes?.filter((a) => a.is_variant_axis) ?? [];
  const defaultOptions = variantAttributes.reduce(
    (acc, attribute) => {
      const key = attribute.handle ?? attribute.id;
      const matched = variant.options?.find(
        (o) => o.option?.title === attribute.name
      );
      acc[key] = matched?.value ?? "";
      return acc;
    },
    {}
  );
  const form = useForm({
    defaultValues: {
      title: variant.title || "",
      sku: variant.sku || "",
      ean: variant.ean || "",
      upc: variant.upc || "",
      barcode: variant.barcode || "",
      weight: variant.weight || "",
      height: variant.height || "",
      width: variant.width || "",
      length: variant.length || "",
      mid_code: variant.mid_code || "",
      hs_code: variant.hs_code || "",
      origin_country: variant.origin_country || "",
      options: defaultOptions
    },
    resolver: zodResolver(ProductEditVariantSchema)
  });
  const { mutateAsync, isPending } = useUpdateProductVariant(
    variant.product_id,
    variant.id
  );
  const handleSubmit = form.handleSubmit(async (data) => {
    const {
      title,
      weight,
      height,
      width,
      length,
      options,
      ...optional
    } = data;
    const nullableData = transformNullableFormData(optional);
    const cleanedOptions = variantAttributes.reduce(
      (acc, attr) => {
        const fieldKey = attr.handle ?? attr.id;
        const v = options?.[fieldKey];
        if (v && attr.name) acc[attr.name] = v;
        return acc;
      },
      {}
    );
    await mutateAsync(
      {
        weight: transformNullableFormNumber(weight),
        height: transformNullableFormNumber(height),
        width: transformNullableFormNumber(width),
        length: transformNullableFormNumber(length),
        title,
        options: Object.keys(cleanedOptions).length ? cleanedOptions : void 0,
        ...nullableData
      },
      {
        onSuccess: () => {
          handleSuccess("../");
          toast.success(
            isProductRequestEnabled ? t("products.edit.requestSuccessToast") : t("products.variant.edit.success")
          );
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex size-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsxs(RouteDrawer.Body, { className: "flex size-full flex-col gap-y-8 overflow-auto", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "title",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { children: t("fields.title") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            variantAttributes.map((attribute) => {
              const fieldKey = attribute.handle ?? attribute.id;
              return /* @__PURE__ */ jsx(
                Form.Field,
                {
                  control: form.control,
                  name: `options.${fieldKey}`,
                  render: ({ field: { value, onChange } }) => {
                    return /* @__PURE__ */ jsxs(Form.Item, { children: [
                      /* @__PURE__ */ jsx(Form.Label, { children: attribute.name }),
                      /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(
                        AttributeValueInput,
                        {
                          type: import_types.AttributeType.SINGLE_SELECT,
                          value: typeof value === "string" ? value : "",
                          onChange,
                          availableValues: (attribute.values ?? []).map(
                            (v) => ({
                              id: v.id,
                              name: v.name
                            })
                          )
                        }
                      ) }),
                      /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                    ] });
                  }
                },
                attribute.id
              );
            })
          ] }),
          /* @__PURE__ */ jsx(Divider, {}),
          /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-8", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "sku",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.sku") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "ean",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.ean") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "upc",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.upc") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "barcode",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.barcode") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            )
          ] }) }),
          /* @__PURE__ */ jsx(Divider, {}),
          /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-x-1", children: [
              /* @__PURE__ */ jsx(Heading, { level: "h2", children: t("products.attributes") }),
              /* @__PURE__ */ jsx(Tooltip, { content: t("products.variant.edit.attributesTooltip"), children: /* @__PURE__ */ jsx(InformationCircleSolid, { className: "text-ui-fg-muted" }) })
            ] }),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "weight",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.weight") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "number", ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "width",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.width") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "number", ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "length",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.length") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "number", ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "height",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.height") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { type: "number", ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "mid_code",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.midCode") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "hs_code",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.hsCode") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(Input, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            ),
            /* @__PURE__ */ jsx(
              Form.Field,
              {
                control: form.control,
                name: "origin_country",
                render: ({ field }) => {
                  return /* @__PURE__ */ jsxs(Form.Item, { children: [
                    /* @__PURE__ */ jsx(Form.Label, { optional: true, children: t("fields.countryOfOrigin") }),
                    /* @__PURE__ */ jsx(Form.Control, { children: /* @__PURE__ */ jsx(CountrySelect, { ...field }) }),
                    /* @__PURE__ */ jsx(Form.ErrorMessage, {})
                  ] });
                }
              }
            )
          ] })
        ] }),
        /* @__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, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { type: "submit", size: "small", isLoading: isPending, children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};

// src/pages/product-variants/product-variant-edit/product-variant-edit.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var ProductVariantEdit = () => {
  const initialData = useLoaderData();
  const { t } = useTranslation2();
  const { id, product_id, variant_id } = useParams();
  const productId = product_id || id;
  const [URLSearchParms] = useSearchParams();
  const searchVariantId = URLSearchParms.get("variant_id");
  const { variant, isPending, isError, error } = useProductVariant(
    productId,
    variant_id || searchVariantId,
    {
      fields: "+options.id,+options.value,+options.option.id,+options.option.title"
    },
    {
      initialData
    }
  );
  const {
    product,
    isPending: isProductPending,
    isError: isProductError,
    error: productError
  } = useProduct(
    variant?.product_id,
    {
      fields: "-variants"
    },
    {
      enabled: !!variant?.product_id
    }
  );
  const ready = !isPending && !!variant && !isProductPending && !!product;
  if (isError) {
    throw error;
  }
  if (isProductError) {
    throw productError;
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { children: /* @__PURE__ */ jsx2(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx2(Heading2, { children: t("products.variant.edit.header") }) }) }),
    ready && /* @__PURE__ */ jsx2(ProductEditVariantForm, { variant, product })
  ] });
};

// src/pages/product-variants/product-variant-edit/loader.ts
var VARIANT_EDIT_FIELDS = "*options,*options.option";
var queryFn = async (id, variantId) => {
  return await sdk.vendor.products.$id.variants.$variantId.query({
    $id: id,
    $variantId: variantId,
    fields: VARIANT_EDIT_FIELDS
  });
};
var editProductVariantQuery = (id, variantId) => ({
  queryKey: variantsQueryKeys.detail(variantId, { fields: VARIANT_EDIT_FIELDS }),
  queryFn: async () => queryFn(id, variantId)
});
var editProductVariantLoader = async ({
  params,
  request
}) => {
  const id = params.product_id || params.id;
  const searchParams = new URL(request.url).searchParams;
  const searchVariantId = searchParams.get("variant_id");
  const variantId = params.variant_id || searchVariantId;
  const query = editProductVariantQuery(id, variantId || searchVariantId);
  return queryClient.getQueryData(query.queryKey) ?? await queryClient.fetchQuery(query);
};
export {
  ProductVariantEdit as Component,
  editProductVariantLoader as loader
};
