import {
  PriceListCreateProductsSchema,
  usePriceListCurrencyData,
  usePriceListGridColumns
} from "./chunk-DTUPDNN3.js";
import {
  exctractPricesFromProducts,
  isProductRow
} from "./chunk-U5MJIHLY.js";
import {
  useProductTableColumns
} from "./chunk-Z5I2Z6L3.js";
import {
  _DataTable,
  useDataTable
} from "./chunk-ULJ3OMWU.js";
import {
  DataGrid
} from "./chunk-U3OWJE7V.js";
import {
  TabbedForm,
  defineTabMeta,
  useTabbedForm
} from "./chunk-KA3VYXNA.js";
import {
  useProductTableFilters
} from "./chunk-WSR2ZXAJ.js";
import {
  useProductTableQuery
} from "./chunk-VVWB3GIK.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-OV7R2AH5.js";
import {
  useBatchPriceListPrices,
  usePriceList
} from "./chunk-K4BGK3CO.js";
import {
  useProducts
} from "./chunk-BA2HXHTW.js";

// src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/schema.ts
import { z } from "zod";
var PriceListPricesAddSchema = z.object({
  product_ids: z.array(z.object({ id: z.string() })).min(1),
  products: PriceListCreateProductsSchema
});
var PriceListPricesAddProductIdsSchema = PriceListPricesAddSchema.pick(
  {
    product_ids: true
  }
);
var PriceListPricesAddProductsIdsFields = Object.keys(
  PriceListPricesAddProductIdsSchema.shape
);
var PriceListPricesAddProductsSchema = PriceListPricesAddSchema.pick({
  products: true
});
var PriceListPricesAddProductsFields = Object.keys(
  PriceListPricesAddProductsSchema.shape
);

// src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx
import { Children as Children2 } from "react";
import { useParams } from "react-router-dom";

// src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { toast } from "@medusajs/ui";
import { Children, useMemo as useMemo2 } from "react";
import { useForm } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsx
import { useEffect } from "react";
import { useWatch } from "react-hook-form";
import { jsx } from "react/jsx-runtime";
var Root = ({
  currencies,
  regions,
  pricePreferences
}) => {
  const form = useTabbedForm();
  const ids = useWatch({
    control: form.control,
    name: "product_ids"
  });
  const existingProducts = useWatch({
    control: form.control,
    name: "products"
  });
  const { products, isLoading, isError, error } = useProducts({
    id: ids.map((id) => id.id),
    limit: ids.length,
    fields: "title,thumbnail,*variants"
  });
  const { setValue } = form;
  const { setCloseOnEscape } = useRouteModal();
  useEffect(() => {
    if (!isLoading && products) {
      products.forEach((product) => {
        if (existingProducts[product.id] || !product.variants) {
          return;
        }
        setValue(`products.${product.id}.variants`, {
          ...product.variants.reduce((variants, variant) => {
            variants[variant.id] = {
              currency_prices: {},
              region_prices: {}
            };
            return variants;
          }, {})
        });
      });
    }
  }, [products, existingProducts, isLoading, setValue]);
  const columns = usePriceListGridColumns({
    currencies,
    regions,
    pricePreferences
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx("div", { className: "flex size-full flex-col divide-y overflow-hidden", children: /* @__PURE__ */ jsx(
    DataGrid,
    {
      isLoading,
      columns,
      data: products,
      getSubRows: (row) => {
        if (isProductRow(row) && row.variants) {
          return row.variants;
        }
      },
      state: form,
      onEditingChange: (editing) => setCloseOnEscape(!editing)
    }
  ) });
};
Root._tabMeta = defineTabMeta({
  id: "price",
  labelKey: "priceLists.create.tabs.prices",
  validationFields: ["products"]
});
var PriceListPricesAddPricesForm = Root;

// src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx
import { Checkbox, Tooltip } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import {
  createColumnHelper
} from "@tanstack/react-table";
import { useMemo, useState } from "react";
import { useWatch as useWatch2 } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { jsx as jsx2 } from "react/jsx-runtime";
var PAGE_SIZE = 50;
var PREFIX = "p";
function getInitialSelection(products) {
  return products.reduce((acc, curr) => {
    acc[curr.id] = true;
    return acc;
  }, {});
}
var Root2 = ({
  priceList
}) => {
  const { t } = useTranslation();
  const form = useTabbedForm();
  const { control, setValue } = form;
  const variantIdMap = useMemo(() => {
    return (priceList.prices ?? []).reduce(
      (acc, curr) => {
        acc[curr.variant_id] = true;
        return acc;
      },
      {}
    );
  }, [priceList.prices]);
  const selectedIds = useWatch2({
    control,
    name: "product_ids"
  });
  const productRecords = useWatch2({
    control,
    name: "products"
  });
  const [rowSelection, setRowSelection] = useState(
    getInitialSelection(selectedIds)
  );
  const { searchParams, raw } = useProductTableQuery({
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  const { products, count, isLoading, isError, error } = useProducts(
    searchParams,
    {
      placeholderData: keepPreviousData
    }
  );
  const updater = (fn) => {
    const state = typeof fn === "function" ? fn(rowSelection) : fn;
    const ids = Object.keys(state);
    const productRecordKeys = Object.keys(productRecords);
    const updatedRecords = productRecordKeys.reduce((acc, key) => {
      if (ids.includes(key)) {
        acc[key] = productRecords[key];
      }
      return acc;
    }, {});
    const update = ids.map((id) => ({ id }));
    setValue("product_ids", update, { shouldDirty: true, shouldTouch: true });
    setValue("products", updatedRecords, {
      shouldDirty: true,
      shouldTouch: true
    });
    setRowSelection(state);
  };
  const columns = useColumns();
  const filters = useProductTableFilters();
  const { table } = useDataTable({
    data: products || [],
    columns,
    count,
    enablePagination: true,
    enableRowSelection: (row) => {
      return !!row.original.variants?.length && !row.original.variants?.some((v) => variantIdMap[v.id]);
    },
    getRowId: (row) => row.id,
    rowSelection: {
      state: rowSelection,
      updater
    },
    pageSize: PAGE_SIZE,
    prefix: PREFIX,
    meta: {
      variantIdMap
    }
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx2("div", { className: "flex size-full flex-col", children: /* @__PURE__ */ jsx2(
    _DataTable,
    {
      table,
      columns,
      filters,
      pageSize: PAGE_SIZE,
      prefix: PREFIX,
      count,
      isLoading,
      layout: "fill",
      orderBy: [
        { key: "title", label: t("fields.title") },
        { key: "status", label: t("fields.status") },
        { key: "created_at", label: t("fields.createdAt") },
        { key: "updated_at", label: t("fields.updatedAt") }
      ],
      pagination: true,
      search: true,
      queryObject: raw
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const base = useProductTableColumns();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row, table }) => {
          const { variantIdMap } = table.options.meta;
          const isPreselected = row.original.variants?.some(
            (v) => variantIdMap[v.id]
          );
          const isDisabled = !row.getCanSelect() || isPreselected;
          const isChecked = row.getIsSelected() || isPreselected;
          const Component = /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: isChecked,
              disabled: isDisabled,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
          if (isPreselected) {
            return /* @__PURE__ */ jsx2(Tooltip, { content: "This product is already in the price list", children: Component });
          }
          if (isDisabled) {
            return /* @__PURE__ */ jsx2(Tooltip, { content: "This product has no variants", children: Component });
          }
          return Component;
        }
      }),
      ...base
    ],
    [base]
  );
};
Root2._tabMeta = defineTabMeta({
  id: "product",
  labelKey: "priceLists.create.tabs.products",
  validationFields: ["product_ids"]
});
var PriceListPricesAddProductIdsForm = Root2;

// src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx
import { jsx as jsx3 } from "react/jsx-runtime";
var PriceListPricesAddForm = ({
  priceList,
  regions,
  currencies,
  pricePreferences,
  children,
  schema,
  defaultValues: extraDefaults
}) => {
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      products: {},
      product_ids: [],
      ...extraDefaults
    },
    resolver: zodResolver(schema ?? PriceListPricesAddSchema)
  });
  const { mutateAsync, isPending } = useBatchPriceListPrices(priceList.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    const { products } = values;
    const prices = exctractPricesFromProducts(products, regions);
    await mutateAsync(
      {
        create: prices
      },
      {
        onSuccess: () => {
          toast.success(t("priceLists.products.add.successToast"));
          handleSuccess();
        },
        onError: (e) => toast.error(e.message)
      }
    );
  });
  const defaultTabs = useMemo2(
    () => [
      /* @__PURE__ */ jsx3(PriceListPricesAddProductIdsForm, { priceList }, "product"),
      /* @__PURE__ */ jsx3(
        PriceListPricesAddPricesForm,
        {
          currencies,
          regions,
          pricePreferences
        },
        "price"
      )
    ],
    [priceList, currencies, regions, pricePreferences]
  );
  const hasCustomChildren = Children.count(children) > 0;
  return /* @__PURE__ */ jsx3(
    TabbedForm,
    {
      form,
      onSubmit: handleSubmit,
      isLoading: isPending,
      children: hasCustomChildren ? children : defaultTabs
    }
  );
};

// src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx
import { jsx as jsx4 } from "react/jsx-runtime";
var Root3 = ({ children }) => {
  const { id } = useParams();
  const { price_list, isPending, isError, error } = usePriceList(id, {
    fields: "*prices"
  });
  const currencyData = usePriceListCurrencyData();
  const ready = currencyData.isReady && !isPending && !!price_list;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx4(RouteFocusModal, { prev: "../..", children: ready && (Children2.count(children) > 0 ? children : /* @__PURE__ */ jsx4(
    PriceListPricesAddForm,
    {
      priceList: price_list,
      ...currencyData
    }
  )) });
};
var PriceListPricesAddPage = Object.assign(Root3, {
  Form: PriceListPricesAddForm,
  ProductIdsTab: PriceListPricesAddProductIdsForm,
  PricesTab: PriceListPricesAddPricesForm,
  Tab: TabbedForm.Tab
});
var PriceListProductsAdd = Root3;

export {
  PriceListPricesAddSchema,
  PriceListPricesAddPage,
  PriceListProductsAdd
};
