import {
  useProductTableColumns
} from "./chunk-AAKR2CB4.js";
import "./chunk-G64YUZSL.js";
import {
  useProductTableQuery
} from "./chunk-BEPAXQMU.js";
import "./chunk-FWPGOIFA.js";
import {
  useProductTableFilters
} from "./chunk-LFX6R456.js";
import "./chunk-DB6ANJBO.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-TKGWSUEI.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import "./chunk-3QSRE5LS.js";
import "./chunk-FQERBIVS.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-7TQNE3E2.js";
import "./chunk-YN3FGNJM.js";
import "./chunk-KCHYLLVG.js";
import "./chunk-CVXKASWV.js";
import "./chunk-THHRRYRS.js";
import "./chunk-LRD242C7.js";
import "./chunk-52KJSIHS.js";
import "./chunk-WIYFXWRI.js";
import "./chunk-INNFZYX2.js";
import "./chunk-QHQWEERJ.js";
import "./chunk-Y7QKP6QU.js";
import "./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 {
  useProductCategory,
  useUpdateProductCategoryProducts
} from "./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 {
  useProducts
} from "./chunk-YAUGB4LD.js";
import "./chunk-A5DJIOHN.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-DTGEFKK4.js";
import "./chunk-NBMM2TZK.js";

// src/pages/categories/[id]/products/index.tsx
import { useParams } from "react-router-dom";

// src/pages/categories/[id]/products/edit-category-products-form/edit-category-products-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var EditCategoryProductsSchema = z.object({
  product_ids: z.array(z.string())
});
var PAGE_SIZE = 50;
var PREFIX = "p";
var EditCategoryProductsForm = ({
  categoryId,
  products = []
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const [selection, setSelection] = useState(
    products.reduce((acc, p) => {
      acc[p.id] = true;
      return acc;
    }, {})
  );
  const form = useForm({
    defaultValues: {
      product_ids: []
    },
    resolver: zodResolver(EditCategoryProductsSchema)
  });
  const updater = (newSelection) => {
    const value = typeof newSelection === "function" ? newSelection(selection) : newSelection;
    form.setValue("product_ids", Object.keys(value), {
      shouldDirty: true,
      shouldTouch: true
    });
    setSelection(value);
  };
  const { searchParams, raw } = useProductTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const {
    products: data,
    count,
    isPending,
    isError,
    error
  } = useProducts({
    ...searchParams
  });
  const columns = useColumns();
  const filters = useProductTableFilters(["categories"]);
  const { table } = useDataTable({
    data,
    columns,
    getRowId: (original) => original.id,
    count,
    pageSize: PAGE_SIZE,
    prefix: PREFIX,
    enableRowSelection: (row) => {
      return !products.some((p) => p.id === row.original.id);
    },
    enablePagination: true,
    rowSelection: {
      state: selection,
      updater
    }
  });
  const { mutateAsync, isPending: isMutating } = useUpdateProductCategoryProducts(categoryId);
  const handleSubmit = form.handleSubmit(async (data2) => {
    await mutateAsync(
      {
        add: data2.product_ids
      },
      {
        onSuccess: () => {
          toast.success(
            t("categories.products.add.successToast", {
              count: data2.product_ids.length - products.length
            })
          );
          handleSuccess();
        },
        onError: (error2) => {
          toast.error(error2.message);
        }
      }
    );
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(
    KeyboundForm,
    {
      onSubmit: handleSubmit,
      className: "flex h-full flex-col overflow-hidden",
      children: [
        /* @__PURE__ */ jsx(RouteFocusModal.Header, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          form.formState.errors.product_ids && /* @__PURE__ */ jsx(Hint, { variant: "error", children: form.formState.errors.product_ids.message }),
          /* @__PURE__ */ jsx(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "small", variant: "secondary", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx(Button, { size: "small", type: "submit", isLoading: isMutating, children: t("actions.save") })
        ] }) }),
        /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "size-full overflow-hidden", children: /* @__PURE__ */ jsx(
          _DataTable,
          {
            table,
            columns,
            pageSize: PAGE_SIZE,
            count,
            queryObject: raw,
            filters,
            orderBy: [
              { key: "title", label: t("fields.title") },
              { key: "created_at", label: t("fields.createdAt") },
              { key: "updated_at", label: t("fields.updatedAt") }
            ],
            prefix: PREFIX,
            isLoading: isPending,
            layout: "fill",
            pagination: true,
            search: "autofocus"
          }
        ) })
      ]
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const { t } = useTranslation();
  const base = useProductTableColumns();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          const isPreSelected = !row.getCanSelect();
          const isSelected = row.getIsSelected() || isPreSelected;
          const Component2 = /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: isSelected,
              disabled: isPreSelected,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
          if (isPreSelected) {
            return /* @__PURE__ */ jsx(
              Tooltip,
              {
                content: t("categories.products.add.disabledTooltip"),
                side: "right",
                children: Component2
              }
            );
          }
          return Component2;
        }
      }),
      ...base
    ],
    [t, base]
  );
};

// src/pages/categories/[id]/products/index.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var Component = () => {
  const { id } = useParams();
  const { product_category, isLoading, isError, error } = useProductCategory(
    id,
    { fields: "*products" }
  );
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { children: !isLoading && product_category && /* @__PURE__ */ jsx2(
    EditCategoryProductsForm,
    {
      categoryId: id,
      products: product_category.products
    }
  ) });
};
export {
  Component
};
