import "./chunk-LQTHYS2Z.mjs";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TWTWTDT.mjs";
import "./chunk-HQKGZADC.mjs";
import "./chunk-EMIHDNB7.mjs";
import "./chunk-XRM7PIRS.mjs";
import {
  useQueryParams
} from "./chunk-C76H5USB.mjs";
import "./chunk-3BQAAPDR.mjs";
import "./chunk-IUCDCPJU.mjs";
import {
  KeyboundForm
} from "./chunk-6HTZNHPT.mjs";
import {
  RouteDrawer
} from "./chunk-OV6YUU3D.mjs";
import {
  useRouteModal
} from "./chunk-ULMMKZ3U.mjs";
import "./chunk-LPEUYMRK.mjs";
import "./chunk-S4DMV3ZT.mjs";
import "./chunk-QJ63TWAK.mjs";
import "./chunk-OBQI23QM.mjs";
import "./chunk-OW2UL5FI.mjs";
import "./chunk-5DUV4AET.mjs";
import "./chunk-FAB3VINY.mjs";
import "./chunk-Q7YBE4IP.mjs";
import "./chunk-HI6URQ7H.mjs";
import "./chunk-6CLQKVAU.mjs";
import "./chunk-KI7TOXBR.mjs";
import "./chunk-QBIQEVTU.mjs";
import "./chunk-WAXMT4IY.mjs";
import "./chunk-DYDGGABK.mjs";
import "./chunk-LGNTHZ5Y.mjs";
import "./chunk-CN7JXSGW.mjs";
import "./chunk-AO2USOOE.mjs";
import "./chunk-KWWLGCSY.mjs";
import "./chunk-5AFMB7XQ.mjs";
import "./chunk-5U6AZEO7.mjs";
import "./chunk-A63RZVX6.mjs";
import "./chunk-HBXV7ENS.mjs";
import "./chunk-ZBMENGLV.mjs";
import "./chunk-LGLPAUIO.mjs";
import "./chunk-CDORR33H.mjs";
import "./chunk-DE44HCDH.mjs";
import "./chunk-MUOBXNL6.mjs";
import "./chunk-BEQ5XTWH.mjs";
import "./chunk-HP2JH45P.mjs";
import "./chunk-VCSSQVPD.mjs";
import "./chunk-SQDIZZDW.mjs";
import {
  useBatchImageVariants,
  useProduct,
  useProductVariants
} from "./chunk-LA2ILUXH.mjs";
import "./chunk-7AXHHXCX.mjs";
import "./chunk-FXYH54JP.mjs";
import "./chunk-774WSTCC.mjs";
import "./chunk-NFEK63OE.mjs";
import "./chunk-QZ7TP4HQ.mjs";

// src/routes/products/product-image-variants-edit/product-image-variants-edit.tsx
import { Heading } from "@medusajs/ui";
import { useTranslation as useTranslation2 } from "react-i18next";
import { json, useParams } from "react-router-dom";

// src/routes/products/product-image-variants-edit/components/variants-table-form/variants-table-form.tsx
import { Button, Checkbox, toast } from "@medusajs/ui";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { keepPreviousData } from "@tanstack/react-query";
import * as zod from "zod";

// src/hooks/table/query/use-product-variant-table-query.tsx
var useProductVariantTableQuery = ({
  prefix,
  pageSize = 20
}) => {
  const queryObject = useQueryParams(
    ["offset", "q", "order", "created_at", "updated_at"],
    prefix
  );
  const { offset, q, order, created_at, updated_at } = queryObject;
  const searchParams = {
    limit: pageSize,
    offset: offset ? Number(offset) : 0,
    order,
    created_at: created_at ? JSON.parse(created_at) : void 0,
    updated_at: updated_at ? JSON.parse(updated_at) : void 0,
    q
  };
  return {
    searchParams,
    raw: queryObject
  };
};

// src/routes/products/product-image-variants-edit/components/variants-table-form/variants-table-form.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var PAGE_SIZE = 20;
var BatchImageVariantsSchema = zod.object({
  variants: zod.array(zod.string())
});
var variantColumnHelper = createColumnHelper();
var VariantsTableForm = ({
  productId,
  image
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const { mutateAsync, isPending } = useBatchImageVariants(productId, image.id);
  const [variantSelection, setVariantSelection] = useState(
    () => image.variants?.reduce((acc, variant) => {
      acc[variant.id] = true;
      return acc;
    }, {}) || {}
  );
  useEffect(() => {
    setVariantSelection(
      image.variants?.reduce((acc, variant) => {
        acc[variant.id] = true;
        return acc;
      }, {}) || {}
    );
  }, [image.variants.length]);
  const form = useForm({
    defaultValues: {
      variants: image.variants?.map((variant) => variant.id) || []
    },
    resolver: zodResolver(BatchImageVariantsSchema)
  });
  const handleSubmit = form.handleSubmit(async () => {
    const initialVariantIds = image?.variants?.map((variant) => variant.id) || [];
    const newVariantIds = Object.keys(variantSelection).filter(
      (k) => variantSelection[k]
    );
    const variantsToAdd = newVariantIds.filter(
      (id) => !initialVariantIds.includes(id)
    );
    const variantsToRemove = initialVariantIds.filter(
      (id) => !newVariantIds.includes(id)
    );
    await mutateAsync(
      {
        add: variantsToAdd,
        remove: variantsToRemove
      },
      {
        onSuccess: () => {
          toast.success(t("products.variantMedia.successToast"));
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const columns = useMemo(
    () => [
      variantColumnHelper.display({
        id: "select",
        header: ({ table: table2 }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table2.getIsSomePageRowsSelected() ? "indeterminate" : table2.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table2.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: row.getIsSelected(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      variantColumnHelper.accessor("title", {
        header: () => t("fields.title"),
        cell: ({ getValue }) => {
          const title = getValue();
          return /* @__PURE__ */ jsx("div", { className: "flex h-full w-full items-center", children: /* @__PURE__ */ jsx("span", { className: "truncate", children: title || "-" }) });
        }
      }),
      variantColumnHelper.accessor("sku", {
        header: () => t("fields.sku"),
        cell: ({ getValue }) => {
          const sku = getValue();
          return /* @__PURE__ */ jsx("div", { className: "flex h-full w-full items-center", children: /* @__PURE__ */ jsx("span", { className: "truncate font-mono text-sm", children: sku || "-" }) });
        }
      }),
      variantColumnHelper.accessor("thumbnail", {
        header: () => t("fields.thumbnail"),
        cell: ({ getValue }) => {
          const isThumbnail = getValue() === image.url;
          return /* @__PURE__ */ jsx("div", { className: "flex h-full w-full items-center", children: /* @__PURE__ */ jsx("span", { className: "truncate text-sm", children: isThumbnail ? t("fields.true") : t("fields.false") }) });
        }
      })
    ],
    [t]
  );
  const updater = (value) => {
    const state = typeof value === "function" ? value(variantSelection) : value;
    setVariantSelection(state);
    const formState = Object.keys(state).filter((k) => state[k]);
    form.setValue("variants", formState, {
      shouldDirty: true,
      shouldTouch: true
    });
  };
  const { searchParams, raw } = useProductVariantTableQuery({
    pageSize: PAGE_SIZE
  });
  const {
    variants,
    count,
    isPending: isLoading
  } = useProductVariants(
    productId,
    {
      ...searchParams
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const { table } = useDataTable({
    data: variants || [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: true,
    pageSize: PAGE_SIZE,
    getRowId: (row) => row.id,
    rowSelection: {
      state: variantSelection,
      updater
    }
  });
  return /* @__PURE__ */ jsx(RouteDrawer.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex flex-1 flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(RouteDrawer.Body, { className: "flex flex-col gap-y-8 overflow-y-auto p-0", children: /* @__PURE__ */ jsx("div", { className: "flex h-full flex-col", children: /* @__PURE__ */ jsx("div", { className: "flex-1 overflow-hidden", children: /* @__PURE__ */ jsx(
          _DataTable,
          {
            layout: "fill",
            table,
            columns,
            count,
            isLoading,
            pageSize: PAGE_SIZE,
            queryObject: raw,
            pagination: true,
            search: true
          }
        ) }) }) }),
        /* @__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,
              disabled: isPending,
              children: t("actions.save")
            }
          )
        ] }) })
      ]
    }
  ) });
};

// src/routes/products/product-image-variants-edit/product-image-variants-edit.tsx
import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var ProductImageVariantsEdit = () => {
  const { t } = useTranslation2();
  const { id: product_id, image_id } = useParams();
  const { product, isPending } = useProduct(
    product_id,
    {
      // TODO: Remove exclusion once we avoid including unnecessary relations by default in the query config
      fields: "images.id,images.url,images.variants.id,-type,-collection,-options,-tags,-variants,-sales_channels"
    },
    {
      enabled: !!product_id && !!image_id
    }
  );
  const image = product?.images?.find((image2) => image2.id === image_id);
  if (!product_id || !image_id || isPending) {
    return null;
  }
  if (!isPending && !image) {
    throw json({ message: `An image with ID ${image_id} was not found` }, 404);
  }
  return /* @__PURE__ */ jsxs2(RouteDrawer, { children: [
    /* @__PURE__ */ jsx2(RouteDrawer.Header, { children: /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-x-4", children: [
      /* @__PURE__ */ jsx2("img", { src: image.url, className: "h-20" }),
      /* @__PURE__ */ jsxs2("div", { children: [
        /* @__PURE__ */ jsx2(RouteDrawer.Title, { asChild: true, children: /* @__PURE__ */ jsx2(Heading, { children: t("products.variantMedia.manageVariants") }) }),
        /* @__PURE__ */ jsx2(RouteDrawer.Description, { children: t("products.variantMedia.manageVariantsDescription") })
      ] })
    ] }) }),
    /* @__PURE__ */ jsx2(
      VariantsTableForm,
      {
        productId: product_id,
        image
      }
    )
  ] });
};
export {
  ProductImageVariantsEdit as Component
};
