import {
  AttributeValueInput
} from "./chunk-6PSJJHI4.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 {
  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 {
  useCreateProductVariant,
  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]/variants/create/index.tsx
import { useParams } from "react-router-dom";

// src/pages/products/[id]/variants/create/create-product-variant-form/create-product-variant-form.tsx
var import_types = __toESM(require_dist(), 1);
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Heading, Input, toast } from "@medusajs/ui";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";

// src/pages/products/[id]/variants/create/create-product-variant-form/constants.ts
import i18next from "i18next";
import { z } from "zod";
var CreateProductVariantSchema = z.object({
  title: z.string().min(1, i18next.t("products.variant.validation.titleRequired")),
  sku: z.string().optional(),
  options: z.record(z.string().min(1, i18next.t("products.variant.validation.optionRequired"))).optional()
});

// src/pages/products/[id]/variants/create/create-product-variant-form/create-product-variant-form.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var CreateProductVariantForm = ({
  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) => {
      acc[attribute.handle ?? attribute.id] = "";
      return acc;
    },
    {}
  );
  const form = useForm({
    defaultValues: {
      title: "",
      sku: "",
      options: defaultOptions
    },
    resolver: zodResolver(CreateProductVariantSchema)
  });
  const { mutateAsync, isPending } = useCreateProductVariant(product.id);
  const handleSubmit = form.handleSubmit(async (data) => {
    const { title, sku, options } = data;
    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(
      {
        title,
        sku: sku || void 0,
        options: Object.keys(cleanedOptions).length ? cleanedOptions : void 0
      },
      {
        onSuccess: () => {
          handleSuccess();
          toast.success(
            isProductRequestEnabled ? t("products.edit.requestSuccessToast") : t("products.variant.create.successToast")
          );
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
    /* @__PURE__ */ jsxs(RouteFocusModal.Header, { children: [
      /* @__PURE__ */ jsx(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("products.variant.create.header") }) }),
      /* @__PURE__ */ jsx(RouteFocusModal.Description, { className: "sr-only", children: t("products.variant.create.header") })
    ] }),
    /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-1 flex-col items-center overflow-y-auto", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8 px-8 py-16", children: [
      /* @__PURE__ */ jsx(Heading, { level: "h1", children: t("products.variant.create.header") }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2", 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,
                    "data-testid": "create-variant-title-input"
                  }
                ) }),
                /* @__PURE__ */ jsx(Form.ErrorMessage, {})
              ] });
            }
          }
        ),
        /* @__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,
                    "data-testid": "create-variant-sku-input"
                  }
                ) }),
                /* @__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(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, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
      /* @__PURE__ */ jsx(
        Button,
        {
          type: "submit",
          variant: "primary",
          size: "small",
          isLoading: isPending,
          "data-testid": "create-variant-submit-button",
          children: t("actions.save")
        }
      )
    ] }) })
  ] }) });
};

// src/pages/products/[id]/variants/create/index.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var Component = () => {
  const { id } = useParams();
  const { product, isLoading, isError, error } = useProduct(
    id,
    PRODUCT_DETAIL_QUERY
  );
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { children: !isLoading && product && /* @__PURE__ */ jsx2(CreateProductVariantForm, { product }) });
};
export {
  Component
};
