import "./chunk-IUCDCPJU.mjs";
import {
  KeyboundForm
} from "./chunk-6HTZNHPT.mjs";
import "./chunk-WVA4O7QS.mjs";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-D6UW7URG.mjs";
import "./chunk-OBQI23QM.mjs";
import {
  useBatchVariantImages,
  useProductVariant,
  useUpdateProductVariant
} from "./chunk-35NDWZ4I.mjs";
import "./chunk-7AXHHXCX.mjs";
import "./chunk-FXYH54JP.mjs";
import "./chunk-774WSTCC.mjs";
import "./chunk-NFEK63OE.mjs";
import "./chunk-QZ7TP4HQ.mjs";

// src/routes/product-variants/product-variant-media/product-variant-media.tsx
import { useParams } from "react-router-dom";

// src/routes/product-variants/product-variant-media/components/edit-product-variant-media-form/edit-product-variant-media-form.tsx
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 EditProductVariantMediaForm = ({
  variant
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const allProductImages = variant.product?.images || [];
  const allVariantImages = (variant.images || []).filter(
    (image) => image.variants?.some((imageVariant) => imageVariant.id === variant.id)
  );
  const unassociatedImages = allProductImages.filter(
    (image) => !image.variants?.some((imageVariant) => imageVariant.id === variant.id)
  );
  const [selection, setSelection] = useState({});
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const form = useForm({
    defaultValues: {
      image_ids: allVariantImages.map((image) => image.id),
      thumbnail: variant.thumbnail
    },
    resolver: zodResolver(MediaSchema)
  });
  const formImageIds = form.watch("image_ids");
  const availableImages = unassociatedImages.filter(
    (image) => !formImageIds.includes(image.id)
  );
  const { mutateAsync: updateVariant } = useUpdateProductVariant(
    variant.product_id,
    variant.id
  );
  const { mutateAsync, isPending } = useBatchVariantImages(
    variant.product_id,
    variant.id
  );
  const handleSubmit = form.handleSubmit(async (data) => {
    const currentVariantImageIds = allVariantImages.map((image) => image.id);
    const newVariantImageIds = data.image_ids;
    const imagesToAdd = newVariantImageIds.filter(
      (id) => !currentVariantImageIds.includes(id)
    );
    const imagesToRemove = currentVariantImageIds.filter(
      (id) => !newVariantImageIds.includes(id)
    );
    if (data.thumbnail !== variant.thumbnail) {
      let thumbnail = data.thumbnail;
      if (thumbnail && ![...currentVariantImageIds, ...newVariantImageIds].includes(thumbnail)) {
        thumbnail = null;
      }
      updateVariant({
        thumbnail: data.thumbnail
      }).catch((error) => {
        toast.error(error.message);
      });
    }
    await mutateAsync(
      {
        add: imagesToAdd,
        remove: imagesToRemove
      },
      {
        onSuccess: () => {
          toast.success(t("products.media.successToast"));
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const handleAddImageToVariant = (imageId) => {
    const currentImageIds = form.getValues("image_ids");
    form.setValue("image_ids", [...currentImageIds, 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: selectedImage.url !== variant.thumbnail,
        shouldTouch: selectedImage.url !== variant.thumbnail
      });
    }
  };
  const handleRemoveSelectedImages = () => {
    const selectedIds = Object.keys(selection);
    if (selectedIds.length === 0) {
      return;
    }
    const currentImageIds = form.getValues("image_ids");
    const newImageIds = currentImageIds.filter(
      (id) => !selectedIds.includes(id)
    );
    form.setValue("image_ids", newImageIds, {
      shouldDirty: true,
      shouldTouch: true
    });
    setSelection({});
  };
  const selectedImageThumbnail = form.watch("thumbnail");
  const isSelectedImageThumbnail = variant.thumbnail && Object.keys(selection).length === 1 && selectedImageThumbnail === variant.images.find((image) => image.id === Object.keys(selection)[0])?.url;
  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__ */ jsxs("div", { className: "bg-ui-bg-subtle flex-1 overflow-auto", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between p-4 lg:hidden", children: [
              /* @__PURE__ */ jsx("h3", { className: "text-sm font-medium", children: t("products.media.variantImages") }),
              /* @__PURE__ */ jsx(
                Button,
                {
                  type: "button",
                  variant: "secondary",
                  size: "small",
                  onClick: () => setIsSidebarOpen(!isSidebarOpen),
                  children: t("products.media.showAvailableImages")
                }
              )
            ] }),
            /* @__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 === form.watch("thumbnail")
              },
              image.id
            )) })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "border-ui-border-base bg-ui-bg-base hidden w-80 border-l lg:block", children: [
            /* @__PURE__ */ jsx("div", { className: "border-ui-border-base border-b p-4", children: /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx("h3", { className: "ui-fg-base ", children: t("products.media.availableImages") }),
              /* @__PURE__ */ jsx("p", { className: "text-ui-fg-muted mt-1 text-sm", children: t("products.media.selectToAdd") })
            ] }) }),
            /* @__PURE__ */ jsx("div", { className: "max-h-[calc(100vh-200px)] overflow-auto", children: /* @__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
            )) }) })
          ] }),
          isSidebarOpen && /* @__PURE__ */ jsx(
            "div",
            {
              className: "fixed inset-0 z-50 bg-black/50 lg:hidden",
              onClick: () => setIsSidebarOpen(false),
              children: /* @__PURE__ */ jsxs(
                "div",
                {
                  className: "bg-ui-bg-base border-ui-border-base absolute right-0 top-0 h-full w-80 border-l",
                  onClick: (e) => e.stopPropagation(),
                  children: [
                    /* @__PURE__ */ jsx("div", { className: "border-ui-border-base border-b p-4", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
                      /* @__PURE__ */ jsxs("div", { children: [
                        /* @__PURE__ */ jsx("h3", { className: "ui-fg-base text-sm font-medium", children: t("products.media.availableImages") }),
                        /* @__PURE__ */ jsx("p", { className: "text-ui-fg-muted mt-1 pr-2 text-xs", children: t("products.media.selectToAdd") })
                      ] }),
                      /* @__PURE__ */ jsx(
                        Button,
                        {
                          variant: "transparent",
                          size: "small",
                          onClick: () => setIsSidebarOpen(false),
                          children: "\xD7"
                        }
                      )
                    ] }) }),
                    /* @__PURE__ */ jsx("div", { className: "max-h-[calc(100vh-200px)] overflow-auto", children: /* @__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(CommandBar, { open: Object.keys(selection).length > 0, children: /* @__PURE__ */ jsxs(CommandBar.Bar, { children: [
          /* @__PURE__ */ jsx(CommandBar.Value, { children: t("general.countSelected", {
            count: Object.keys(selection).length
          }) }),
          /* @__PURE__ */ jsx(CommandBar.Seperator, {}),
          Object.keys(selection).length === 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 handleToggle = useCallback(
    (value) => {
      onCheckedChange(value);
    },
    [onCheckedChange]
  );
  const { t } = useTranslation();
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: clx(
        "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: handleToggle
              }
            )
          }
        ),
        /* @__PURE__ */ jsx("img", { src: media.url, className: "size-full object-cover object-center" })
      ]
    }
  );
};
var UnassociatedImageItem = ({
  media,
  onAdd
}) => {
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: clx(
        "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: clx(
              "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": true
              }
            ),
            children: /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-base border-ui-border-base flex h-12 w-12 items-center justify-center rounded-full border shadow-lg", children: /* @__PURE__ */ jsx(Plus, {}) })
          }
        ),
        /* @__PURE__ */ jsx("img", { src: media.url, className: "size-full object-cover object-center" })
      ]
    }
  );
};

// src/routes/product-variants/product-variant-media/product-variant-media.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var ProductVariantMedia = () => {
  const { id, variant_id } = useParams();
  const { variant, isFetching, isError, error } = useProductVariant(
    id,
    variant_id,
    {
      fields: "*product,*product.images,*images,+images.variants.id"
    }
  );
  const ready = !isFetching && variant;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { children: ready && /* @__PURE__ */ jsx2(
    EditProductVariantMediaForm,
    {
      variant
    }
  ) });
};
export {
  ProductVariantMedia as Component
};
