import {
  VARIANT_DETAIL_FIELDS
} from "./chunk-RSOV55K7.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import "./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 {
  useProductVariant,
  useUpdateProductVariant
} 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/product-variants/product-variant-detail/media/index.tsx
import { useTranslation as useTranslation2 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/product-variants/product-variant-detail/media/edit-variant-media-form/edit-variant-media-form.tsx
var import_types = __toESM(require_dist(), 1);
import { zodResolver } from "@hookform/resolvers/zod";
import { Plus, ThumbnailBadge } from "@medusajs/icons";
import { Button, Checkbox, clx, CommandBar, toast, Tooltip } from "@medusajs/ui";
import { Fragment, useCallback, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var MediaSchema = z.object({
  image_ids: z.array(z.string()),
  thumbnail: z.string().nullable()
});
var EditVariantMediaForm = ({
  variant
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { feature_flags } = useFeatureFlags();
  const isProductRequestEnabled = !!feature_flags?.[import_types.MercurFeatureFlags.PRODUCT_REQUEST];
  const allProductImages = variant.product?.images ?? [];
  const variantImageIds = allProductImages.filter((image) => (image.variants ?? []).some((v) => v.id === variant.id)).map((image) => image.id);
  const [selection, setSelection] = useState({});
  const form = useForm({
    defaultValues: {
      image_ids: variantImageIds,
      thumbnail: variant.thumbnail ?? null
    },
    resolver: zodResolver(MediaSchema)
  });
  const formImageIds = form.watch("image_ids");
  const formThumbnail = form.watch("thumbnail");
  const availableImages = allProductImages.filter(
    (image) => !formImageIds.includes(image.id)
  );
  const { mutateAsync, isPending } = useUpdateProductVariant(
    variant.product_id,
    variant.id
  );
  const handleSubmit = form.handleSubmit(async (data) => {
    const add = data.image_ids.filter((id) => !variantImageIds.includes(id));
    const remove = variantImageIds.filter((id) => !data.image_ids.includes(id));
    const selectedUrls = new Set(
      allProductImages.filter((image) => data.image_ids.includes(image.id)).map((image) => image.url)
    );
    const thumbnail = data.thumbnail && selectedUrls.has(data.thumbnail) ? data.thumbnail : null;
    await mutateAsync(
      {
        images: { add, remove },
        thumbnail
      },
      {
        onSuccess: () => {
          toast.success(
            isProductRequestEnabled ? t("products.edit.requestSuccessToast") : t("products.media.successToast")
          );
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const handleAddImageToVariant = (imageId) => {
    form.setValue("image_ids", [...form.getValues("image_ids"), imageId], {
      shouldDirty: true,
      shouldTouch: true
    });
  };
  const handleCheckedChange = useCallback(
    (id) => {
      return (val) => {
        if (!val) {
          const { [id]: _, ...rest } = selection;
          setSelection(rest);
        } else {
          setSelection((prev) => ({ ...prev, [id]: true }));
        }
      };
    },
    [selection]
  );
  const handlePromoteToThumbnail = () => {
    const ids = Object.keys(selection);
    if (!ids.length) {
      return;
    }
    const selectedImage = allProductImages.find((image) => image.id === ids[0]);
    if (selectedImage) {
      form.setValue("thumbnail", selectedImage.url, {
        shouldDirty: true,
        shouldTouch: true
      });
    }
    setSelection({});
  };
  const handleRemoveSelectedImages = () => {
    const selectedIds = Object.keys(selection);
    if (!selectedIds.length) {
      return;
    }
    form.setValue(
      "image_ids",
      form.getValues("image_ids").filter((id) => !selectedIds.includes(id)),
      { shouldDirty: true, shouldTouch: true }
    );
    setSelection({});
  };
  const selectionCount = Object.keys(selection).length;
  const isSelectedImageThumbnail = selectionCount === 1 && allProductImages.find((image) => image.id === Object.keys(selection)[0])?.url === formThumbnail;
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { blockSearchParams: true, form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      className: "flex size-full flex-col overflow-hidden",
      onSubmit: handleSubmit,
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-col overflow-hidden", children: /* @__PURE__ */ jsxs("div", { className: "relative flex size-full", children: [
          /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-subtle flex-1 overflow-auto", children: /* @__PURE__ */ jsx("div", { className: "grid h-fit auto-rows-auto grid-cols-2 gap-4 p-4 sm:grid-cols-3 lg:grid-cols-6 lg:gap-6 lg:p-6", children: allProductImages.filter((image) => formImageIds.includes(image.id)).map((image) => /* @__PURE__ */ jsx(
            MediaGridItem,
            {
              media: image,
              checked: !!selection[image.id],
              onCheckedChange: handleCheckedChange(image.id),
              isThumbnail: image.url === formThumbnail
            },
            image.id
          )) }) }),
          /* @__PURE__ */ jsxs("div", { className: "border-ui-border-base bg-ui-bg-base hidden w-80 border-l lg:block", children: [
            /* @__PURE__ */ jsxs("div", { className: "border-ui-border-base flex flex-col gap-y-1 border-b px-4 py-4", children: [
              /* @__PURE__ */ jsx("span", { className: "text-ui-fg-base txt-compact-small-plus", children: t("products.media.availableImages") }),
              /* @__PURE__ */ jsx("span", { className: "text-ui-fg-muted txt-small", children: t("products.media.selectToAdd") })
            ] }),
            /* @__PURE__ */ jsx("div", { className: "overflow-auto", children: availableImages.length ? /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-4 p-4", children: availableImages.map((image) => /* @__PURE__ */ jsx(
              UnassociatedImageItem,
              {
                media: image,
                onAdd: () => handleAddImageToVariant(image.id)
              },
              image.id
            )) }) : /* @__PURE__ */ jsx("div", { className: "text-ui-fg-muted txt-small px-4 py-6", children: t("products.media.emptyState.description") }) })
          ] })
        ] }) }),
        /* @__PURE__ */ jsx(CommandBar, { open: !!selectionCount, children: /* @__PURE__ */ jsxs(CommandBar.Bar, { children: [
          /* @__PURE__ */ jsx(CommandBar.Value, { children: t("general.countSelected", { count: selectionCount }) }),
          /* @__PURE__ */ jsx(CommandBar.Seperator, {}),
          selectionCount === 1 && !isSelectedImageThumbnail && /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(
              CommandBar.Command,
              {
                action: handlePromoteToThumbnail,
                label: t("products.media.makeThumbnail"),
                shortcut: "t"
              }
            ),
            /* @__PURE__ */ jsx(CommandBar.Seperator, {})
          ] }),
          /* @__PURE__ */ jsx(
            CommandBar.Command,
            {
              action: handleRemoveSelectedImages,
              label: t("products.media.removeSelected"),
              shortcut: "r"
            }
          )
        ] }) }),
        /* @__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, { size: "small", type: "submit", isLoading: isPending, children: t("actions.save") })
        ] }) })
      ]
    }
  ) });
};
var MediaGridItem = ({
  media,
  checked,
  onCheckedChange,
  isThumbnail
}) => {
  const { t } = useTranslation();
  return /* @__PURE__ */ jsxs("div", { className: "shadow-elevation-card-rest hover:shadow-elevation-card-hover focus-visible:shadow-borders-focus bg-ui-bg-subtle-hover group relative aspect-square h-auto max-w-full overflow-hidden rounded-lg outline-none", children: [
    isThumbnail && /* @__PURE__ */ jsx("div", { className: "absolute left-2 top-2", children: /* @__PURE__ */ jsx(Tooltip, { content: t("products.media.thumbnailTooltip"), children: /* @__PURE__ */ jsx(ThumbnailBadge, {}) }) }),
    /* @__PURE__ */ jsx(
      "div",
      {
        className: clx("transition-fg absolute right-2 top-2 opacity-0", {
          "group-focus-within:opacity-100 group-hover:opacity-100 group-focus:opacity-100": !checked,
          "opacity-100": checked
        }),
        children: /* @__PURE__ */ jsx(
          Checkbox,
          {
            onClick: (e) => e.stopPropagation(),
            checked,
            onCheckedChange
          }
        )
      }
    ),
    /* @__PURE__ */ jsx(
      "img",
      {
        src: media.url,
        alt: "",
        className: "size-full object-cover object-center"
      }
    )
  ] });
};
var UnassociatedImageItem = ({
  media,
  onAdd
}) => {
  return /* @__PURE__ */ jsxs(
    "button",
    {
      type: "button",
      "aria-label": "Variant media file input",
      className: "shadow-elevation-card-rest hover:shadow-elevation-card-hover focus-visible:shadow-borders-focus bg-ui-bg-subtle-hover group relative aspect-square h-auto max-w-full cursor-pointer overflow-hidden rounded-lg outline-none",
      onClick: onAdd,
      children: [
        /* @__PURE__ */ jsx("div", { className: "transition-fg absolute inset-0 flex items-center justify-center bg-black/30 opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 group-focus:opacity-100", children: /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-base border-ui-border-base shadow-elevation-card-rest flex h-12 w-12 items-center justify-center rounded-full border", children: /* @__PURE__ */ jsx(Plus, {}) }) }),
        /* @__PURE__ */ jsx(
          "img",
          {
            src: media.url,
            alt: "",
            className: "size-full object-cover object-center"
          }
        )
      ]
    }
  );
};

// src/pages/product-variants/product-variant-detail/media/index.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var Component = () => {
  const { t } = useTranslation2();
  const { id, product_id, variant_id } = useParams();
  const productId = id || product_id;
  const { variant, isLoading, isError, error } = useProductVariant(
    productId,
    variant_id,
    { fields: VARIANT_DETAIL_FIELDS }
  );
  if (isError) {
    throw error;
  }
  const ready = !isLoading && !!variant;
  return /* @__PURE__ */ jsxs2(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx2(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx2("span", { className: "sr-only", children: t("products.media.label") }) }),
    /* @__PURE__ */ jsx2(RouteFocusModal.Description, { asChild: true, children: /* @__PURE__ */ jsx2("span", { className: "sr-only", children: t("products.media.editHint") }) }),
    ready && /* @__PURE__ */ jsx2(EditVariantMediaForm, { variant })
  ] });
};
export {
  Component
};
