import {
  useProductTableColumns
} from "./chunk-Z5I2Z6L3.js";
import "./chunk-FWPGOIFA.js";
import "./chunk-DB6ANJBO.js";
import "./chunk-PHOCVOZ5.js";
import "./chunk-WIYFXWRI.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-KYPPQGGE.js";
import "./chunk-ZMC7BKLT.js";
import "./chunk-KAZ5BYTQ.js";
import "./chunk-634XVU3D.js";
import {
  KeyboundForm
} from "./chunk-U2ZFCAPX.js";
import "./chunk-INNFZYX2.js";
import "./chunk-Y7QKP6QU.js";
import {
  useProductTableFilters
} from "./chunk-LNAXUDW2.js";
import {
  useProductTableQuery
} from "./chunk-VVWB3GIK.js";
import "./chunk-HKDFWQ6Q.js";
import "./chunk-SESTTUVM.js";
import "./chunk-THHRRYRS.js";
import "./chunk-UZWFZMOX.js";
import "./chunk-XQNVC4Q7.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-FWJLS7XD.js";
import "./chunk-3QSRE5LS.js";
import "./chunk-PBQ5M44A.js";
import "./chunk-OH4AABUT.js";
import "./chunk-YKDEE7ZL.js";
import "./chunk-AEMDNTW5.js";
import "./chunk-LYD3C73Z.js";
import "./chunk-7O5NDICV.js";
import "./chunk-46M463BR.js";
import "./chunk-YFRC6GEN.js";
import "./chunk-N6SI4IIT.js";
import "./chunk-JPNPTILP.js";
import "./chunk-DAXXLQKB.js";
import "./chunk-OHOWEMHO.js";
import "./chunk-GKGLVDDV.js";
import "./chunk-WJJXUXSO.js";
import "./chunk-LAPEZATU.js";
import "./chunk-DBNPVU3L.js";
import {
  useCollection,
  useUpdateCollectionProducts
} from "./chunk-U7WZYWGA.js";
import "./chunk-ZN7LWXVC.js";
import "./chunk-VYMODH6P.js";
import "./chunk-LEG67A2R.js";
import "./chunk-PRBE5CM3.js";
import "./chunk-5TRY5IMZ.js";
import "./chunk-TAKEQAZZ.js";
import "./chunk-B6FG7A6W.js";
import "./chunk-EPHVGD5Z.js";
import "./chunk-ESPLVOFC.js";
import "./chunk-FXWKGNRV.js";
import "./chunk-VDKOJ5WD.js";
import "./chunk-DL2ZIXBO.js";
import "./chunk-Z2QQZOG3.js";
import {
  useProducts
} from "./chunk-5CK6XEFV.js";
import "./chunk-RHKRREUU.js";
import "./chunk-ZA2KFUFR.js";
import "./chunk-ZBWL72TB.js";
import "./chunk-NBMM2TZK.js";

// src/pages/collections/collection-add-products/collection-add-products.tsx
import { useParams } from "react-router-dom";

// src/pages/collections/collection-add-products/components/add-products-to-collection-form/add-products-to-collection-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useEffect, useMemo, useState } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import * as zod from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var AddProductsToCollectionSchema = zod.object({
  add: zod.array(zod.string()).min(1)
});
var PAGE_SIZE = 50;
var PREFIX = "p";
var AddProductsToCollectionForm = ({
  collection
}) => {
  const { t } = useTranslation();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      add: []
    },
    resolver: zodResolver(AddProductsToCollectionSchema)
  });
  const { setValue } = form;
  const { mutateAsync, isPending: isMutating } = useUpdateCollectionProducts(
    collection.id
  );
  const [rowSelection, setRowSelection] = useState({});
  const updater = (newSelection) => {
    const update = typeof newSelection === "function" ? newSelection(rowSelection) : newSelection;
    setValue(
      "add",
      Object.keys(update).filter((k) => update[k]),
      {
        shouldDirty: true,
        shouldTouch: true
      }
    );
    setRowSelection(update);
  };
  useEffect(() => {
    setValue(
      "add",
      Object.keys(rowSelection).filter((k) => rowSelection[k]),
      {
        shouldDirty: true,
        shouldTouch: true
      }
    );
  }, [rowSelection, setValue]);
  const { searchParams, raw } = useProductTableQuery({
    prefix: PREFIX,
    pageSize: PAGE_SIZE
  });
  const { products, count, isLoading, isError, error } = useProducts(
    {
      fields: "*variants,*sales_channels",
      ...searchParams
    },
    {
      placeholderData: keepPreviousData
    }
  );
  const columns = useColumns();
  const filters = useProductTableFilters(["collections"]);
  const { table } = useDataTable({
    data: products ?? [],
    columns,
    count,
    pageSize: PAGE_SIZE,
    prefix: PREFIX,
    getRowId: (row) => row.id,
    enableRowSelection: true,
    rowSelection: {
      state: rowSelection,
      updater
    },
    enablePagination: true,
    meta: {
      collectionId: collection.id
    }
  });
  const handleSubmit = form.handleSubmit(async (values) => {
    await mutateAsync(
      {
        add: values.add
      },
      {
        onSuccess: () => {
          toast.success(
            t("collections.products.add.successToast", {
              count: values.add.length
            })
          );
          handleSuccess();
        },
        onError: (e) => {
          toast.error(e.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__ */ jsx("div", { className: "flex items-center justify-end gap-x-2", children: form.formState.errors.add && /* @__PURE__ */ jsx(Hint, { variant: "error", children: form.formState.errors.add.message }) }) }),
        /* @__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,
            layout: "fill",
            pagination: true,
            search: "autofocus"
          }
        ) }),
        /* @__PURE__ */ jsxs(RouteFocusModal.Footer, { children: [
          /* @__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") })
        ] })
      ]
    }
  ) });
};
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, table }) => {
          const { collectionId } = table.options.meta;
          const isAdded = row.original.collection_id === collectionId;
          const isSelected = row.getIsSelected() || isAdded;
          const Component = /* @__PURE__ */ jsx(
            Checkbox,
            {
              checked: isSelected,
              disabled: isAdded,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
          if (isAdded) {
            return /* @__PURE__ */ jsx(
              Tooltip,
              {
                content: t("salesChannels.productAlreadyAdded"),
                side: "right",
                children: Component
              }
            );
          }
          return Component;
        }
      }),
      ...base
    ],
    [t, base]
  );
};

// src/pages/collections/collection-add-products/collection-add-products.tsx
import { jsx as jsx2 } from "react/jsx-runtime";
var CollectionAddProducts = () => {
  const { id } = useParams();
  const { collection, isLoading, isError, error } = useCollection(id);
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2(RouteFocusModal, { children: !isLoading && collection && /* @__PURE__ */ jsx2(AddProductsToCollectionForm, { collection }) });
};
export {
  CollectionAddProducts as Component
};
