import {
  PriceListCreateProductsSchema,
  usePriceListCurrencyData,
  usePriceListGridColumns
} from "./chunk-X6ZQMFCT.js";
import "./chunk-N335VHD3.js";
import "./chunk-EBZ5VZEO.js";
import "./chunk-4F5GP7J7.js";
import {
  exctractPricesFromProducts,
  isProductRow
} from "./chunk-BNOKKKUU.js";
import "./chunk-6IJMSVC6.js";
import "./chunk-7TIZP4YG.js";
import "./chunk-GJM5XI3E.js";
import "./chunk-YNGA3GRX.js";
import "./chunk-BI2AYXZQ.js";
import "./chunk-MG4GKUJW.js";
import "./chunk-AYVH6Q5O.js";
import "./chunk-VOHEQ7B5.js";
import "./chunk-DY3XQPHC.js";
import "./chunk-GRH7C3QN.js";
import "./chunk-VKOE5J66.js";
import "./chunk-42R54Z2X.js";
import "./chunk-Y6S7K3YB.js";
import "./chunk-N3T24SEK.js";
import "./chunk-JHIMVLB2.js";
import "./chunk-HRUO43BZ.js";
import "./chunk-HHD2VUED.js";
import "./chunk-2ZFELO2L.js";
import "./chunk-26OOAKQ6.js";
import "./chunk-S2WEYEQR.js";
import "./chunk-XBKWFLJG.js";
import "./chunk-5ALC4Z2H.js";
import "./chunk-ZC2ME3UB.js";
import "./chunk-CMHI2RPL.js";
import "./chunk-HB3BP55W.js";
import "./chunk-SYNUA6LQ.js";
import "./chunk-UAE6XBYL.js";
import "./chunk-5YZ3G5EZ.js";
import "./chunk-VW56KWO2.js";
import "./chunk-T35QBLG7.js";
import "./chunk-XCHKUSUU.js";
import "./chunk-JRTZWK77.js";
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 {
  DataGrid
} from "./chunk-5FBQOAXU.js";
import "./chunk-IQPN4PZJ.js";
import "./chunk-SMQT3ZNO.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-LAVHRER2.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 {
  useBatchPriceListPrices,
  usePriceList
} from "./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 "./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/price-lists/[id]/products/add/index.tsx
import { useTranslation as useTranslation3 } from "react-i18next";
import { useParams } from "react-router-dom";

// src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsx
import { useState as useState2 } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, ProgressTabs, toast } from "@medusajs/ui";
import { useForm } from "react-hook-form";
import { useTranslation as useTranslation2 } from "react-i18next";

// src/pages/price-lists/[id]/products/add/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 PriceListPricesAddPricesForm = ({
  form,
  currencies,
  regions,
  pricePreferences
}) => {
  const ids = useWatch({
    control: form.control,
    name: "product_ids"
  });
  const existingProducts = useWatch({
    control: form.control,
    name: "products"
  });
  const {
    products: productsRaw,
    isLoading,
    isError,
    error
  } = useProducts({
    fields: "title,thumbnail,*variants,+status, *variants.prices"
  });
  const products = productsRaw?.filter((product) => ids.some((id) => id.id === product.id));
  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,
    showCurrentPriceCell: true
  });
  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)
    }
  ) });
};

// src/pages/price-lists/[id]/products/add/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 PriceListPricesAddProductIdsForm = ({
  priceList,
  form
}) => {
  const { t } = useTranslation();
  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 { t } = useTranslation();
  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 Component2 = /* @__PURE__ */ jsx2(
            Checkbox,
            {
              checked: isChecked,
              disabled: isDisabled,
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
          if (isPreselected) {
            return /* @__PURE__ */ jsx2(Tooltip, { content: t("priceLists.products.add.alreadyInPriceList"), children: Component2 });
          }
          if (isDisabled) {
            return /* @__PURE__ */ jsx2(Tooltip, { content: t("priceLists.products.add.noVariants"), children: Component2 });
          }
          return Component2;
        }
      }),
      ...base
    ],
    [base, t]
  );
};

// src/pages/price-lists/[id]/products/add/price-list-prices-add-form/schema.ts
import i18n from "i18next";
import { z } from "zod";
var PriceListPricesAddBaseSchema = z.object({
  product_ids: z.array(z.object({ id: z.string() })).min(1),
  products: PriceListCreateProductsSchema
});
var PriceListPricesAddProductIdsSchema = PriceListPricesAddBaseSchema.pick({
  product_ids: true
});
var PriceListPricesAddProductsIdsFields = Object.keys(
  PriceListPricesAddProductIdsSchema.shape
);
var PriceListPricesAddProductsSchema = PriceListPricesAddBaseSchema.pick({
  products: true
});
var PriceListPricesAddProductsFields = Object.keys(
  PriceListPricesAddProductsSchema.shape
);
var PriceListPricesAddSchema = PriceListPricesAddBaseSchema.refine(
  (data) => {
    const productIds = data.product_ids.map((p) => p.id);
    for (const productId of productIds) {
      const product = data.products[productId];
      if (!product) continue;
      for (const variant of Object.values(product.variants || {})) {
        const hasCurrencyPrice = Object.values(variant.currency_prices || {}).some((price) => {
          const amount = price?.amount;
          return amount !== void 0 && amount !== null && amount !== "" && (typeof amount === "number" ? amount > 0 : String(amount).trim() !== "");
        });
        const hasRegionPrice = Object.values(variant.region_prices || {}).some((price) => {
          const amount = price?.amount;
          return amount !== void 0 && amount !== null && amount !== "" && (typeof amount === "number" ? amount > 0 : String(amount).trim() !== "");
        });
        if (hasCurrencyPrice || hasRegionPrice) {
          return true;
        }
      }
    }
    return false;
  },
  {
    message: i18n.t("validation.atLeastOnePrice"),
    path: ["products"]
  }
);

// src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsx
import { jsx as jsx3, jsxs } from "react/jsx-runtime";
var tabOrder = ["product" /* PRODUCT */, "price" /* PRICE */];
var initialTabState = {
  ["product" /* PRODUCT */]: "in-progress",
  ["price" /* PRICE */]: "not-started"
};
var PriceListPricesAddForm = ({
  priceList,
  regions,
  currencies,
  pricePreferences
}) => {
  const [tab, setTab] = useState2("product" /* PRODUCT */);
  const [tabState, setTabState] = useState2(initialTabState);
  const { t } = useTranslation2();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      products: {},
      product_ids: []
    },
    resolver: zodResolver(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)
        }
      );
    },
    (errors) => {
      if (errors.products) {
        toast.error(t("priceLists.products.add.atLeastOnePrice"));
      }
    }
  );
  const partialFormValidation = (fields, schema) => {
    form.clearErrors(fields);
    const values = fields.reduce(
      (acc, key) => {
        acc[key] = form.getValues(key);
        return acc;
      },
      {}
    );
    const validationResult = schema.safeParse(values);
    if (!validationResult.success) {
      validationResult.error.errors.forEach(({ path, message, code }) => {
        form.setError(path.join("."), {
          type: code,
          message
        });
      });
      return false;
    }
    return true;
  };
  const isTabDirty = (tab2) => {
    switch (tab2) {
      case "product" /* PRODUCT */: {
        const fields = PriceListPricesAddProductsIdsFields;
        return fields.some((field) => {
          return form.getFieldState(field).isDirty;
        });
      }
      case "price" /* PRICE */: {
        const fields = PriceListPricesAddProductsFields;
        return fields.some((field) => {
          return form.getFieldState(field).isDirty;
        });
      }
    }
  };
  const handleChangeTab = (update) => {
    if (tab === update) {
      return;
    }
    if (tabOrder.indexOf(update) < tabOrder.indexOf(tab)) {
      const isCurrentTabDirty = isTabDirty(tab);
      setTabState((prev) => ({
        ...prev,
        [tab]: isCurrentTabDirty ? prev[tab] : "not-started",
        [update]: "in-progress"
      }));
      setTab(update);
      return;
    }
    const tabs = tabOrder.slice(0, tabOrder.indexOf(update));
    for (const tab2 of tabs) {
      if (tab2 === "product" /* PRODUCT */) {
        if (!partialFormValidation(
          PriceListPricesAddProductsIdsFields,
          PriceListPricesAddProductIdsSchema
        )) {
          setTabState((prev) => ({
            ...prev,
            [tab2]: "in-progress"
          }));
          setTab(tab2);
          return;
        }
        setTabState((prev) => ({
          ...prev,
          [tab2]: "completed"
        }));
      }
    }
    setTabState((prev) => ({
      ...prev,
      [tab]: "completed",
      [update]: "in-progress"
    }));
    setTab(update);
  };
  const handleNextTab = (tab2) => {
    if (tabOrder.indexOf(tab2) + 1 >= tabOrder.length) {
      return;
    }
    const nextTab = tabOrder[tabOrder.indexOf(tab2) + 1];
    handleChangeTab(nextTab);
  };
  return /* @__PURE__ */ jsx3(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsx3(
    ProgressTabs,
    {
      value: tab,
      onValueChange: (tab2) => handleChangeTab(tab2),
      className: "flex h-full flex-col overflow-hidden",
      children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex h-full flex-col", children: [
        /* @__PURE__ */ jsx3(RouteFocusModal.Header, { children: /* @__PURE__ */ jsx3("div", { className: "flex w-full items-center justify-between gap-x-4", children: /* @__PURE__ */ jsx3("div", { className: "-my-2 w-full max-w-[600px] border-l", children: /* @__PURE__ */ jsxs(ProgressTabs.List, { className: "grid w-full grid-cols-3", children: [
          /* @__PURE__ */ jsx3(
            ProgressTabs.Trigger,
            {
              status: tabState.product,
              value: "product" /* PRODUCT */,
              children: t("priceLists.create.tabs.products")
            }
          ),
          /* @__PURE__ */ jsx3(
            ProgressTabs.Trigger,
            {
              status: tabState.price,
              value: "price" /* PRICE */,
              children: t("priceLists.create.tabs.prices")
            }
          )
        ] }) }) }) }),
        /* @__PURE__ */ jsxs(RouteFocusModal.Body, { className: "size-full overflow-hidden", children: [
          /* @__PURE__ */ jsx3(
            ProgressTabs.Content,
            {
              className: "size-full overflow-y-auto",
              value: "product" /* PRODUCT */,
              children: /* @__PURE__ */ jsx3(
                PriceListPricesAddProductIdsForm,
                {
                  form,
                  priceList
                }
              )
            }
          ),
          /* @__PURE__ */ jsx3(
            ProgressTabs.Content,
            {
              className: "size-full overflow-hidden",
              value: "price" /* PRICE */,
              children: /* @__PURE__ */ jsx3(
                PriceListPricesAddPricesForm,
                {
                  form,
                  regions,
                  currencies,
                  pricePreferences
                }
              )
            }
          )
        ] }),
        /* @__PURE__ */ jsx3(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", children: [
          /* @__PURE__ */ jsx3(RouteFocusModal.Close, { asChild: true, children: /* @__PURE__ */ jsx3(Button, { variant: "secondary", size: "small", children: t("actions.cancel") }) }),
          /* @__PURE__ */ jsx3(
            PrimaryButton,
            {
              tab,
              next: handleNextTab,
              isLoading: isPending
            }
          )
        ] }) })
      ] })
    }
  ) });
};
var PrimaryButton = ({ tab, next, isLoading }) => {
  const { t } = useTranslation2();
  if (tab === "price" /* PRICE */) {
    return /* @__PURE__ */ jsx3(
      Button,
      {
        type: "submit",
        variant: "primary",
        size: "small",
        isLoading,
        children: t("actions.save")
      },
      "submit-button"
    );
  }
  return /* @__PURE__ */ jsx3(
    Button,
    {
      type: "button",
      variant: "primary",
      size: "small",
      onClick: () => next(tab),
      children: t("actions.continue")
    },
    "next-button"
  );
};

// src/pages/price-lists/[id]/products/add/index.tsx
import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
var Component = () => {
  const { t } = useTranslation3();
  const { id } = useParams();
  const { price_list, isPending, isError, error } = usePriceList(id);
  const currencyData = usePriceListCurrencyData();
  const ready = currencyData.isReady && !isPending && !!price_list;
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsxs2(RouteFocusModal, { children: [
    /* @__PURE__ */ jsx4(RouteFocusModal.Title, { asChild: true, children: /* @__PURE__ */ jsx4("span", { className: "sr-only", children: t("priceLists.products.add.title") }) }),
    /* @__PURE__ */ jsx4(RouteFocusModal.Description, { className: "sr-only", children: t("priceLists.products.add.description") }),
    ready && /* @__PURE__ */ jsx4(PriceListPricesAddForm, { priceList: price_list, ...currencyData })
  ] });
};
export {
  Component
};
