import {
  PriceListCreateProductsSchema,
  PriceListRulesSchema,
  usePriceListCurrencyData,
  usePriceListGridColumns
} from "./chunk-DTUPDNN3.js";
import {
  exctractPricesFromProducts,
  isProductRow
} from "./chunk-U5MJIHLY.js";
import {
  PriceListCustomerGroupRuleForm
} from "./chunk-76FXHSMH.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 {
  useDocumentDirection
} from "./chunk-Y7QKP6QU.js";
import {
  useProductTableFilters
} from "./chunk-WSR2ZXAJ.js";
import {
  useProductTableQuery
} from "./chunk-VVWB3GIK.js";
import {
  RouteFocusModal,
  StackedFocusModal,
  useRouteModal,
  useStackedModal
} from "./chunk-OV7R2AH5.js";
import {
  Form
} from "./chunk-3QSRE5LS.js";
import {
  useCreatePriceList
} from "./chunk-K4BGK3CO.js";
import {
  useProducts
} from "./chunk-BA2HXHTW.js";

// src/pages/price-lists/price-list-create/components/price-list-create-form/schema.ts
import { z } from "zod";
var PricingCustomerGroupsArray = z.array(
  z.object({
    id: z.string(),
    name: z.string()
  })
);
var PricingCreateSchema = z.object({
  type: z.enum(["sale", "override"]),
  status: z.enum(["draft", "active"]),
  title: z.string().min(1),
  description: z.string().min(1),
  starts_at: z.date().nullish(),
  ends_at: z.date().nullish(),
  product_ids: z.array(z.object({ id: z.string() })).min(1),
  products: PriceListCreateProductsSchema,
  rules: PriceListRulesSchema.nullish()
});
var PricingDetailsSchema = PricingCreateSchema.pick({
  type: true,
  title: true,
  description: true,
  starts_at: true,
  ends_at: true
});
var PricingDetailsFields = Object.keys(
  PricingDetailsSchema.shape
);
var PricingProductsSchema = PricingCreateSchema.pick({
  product_ids: true
});
var PricingProductsFields = Object.keys(
  PricingProductsSchema.shape
);
var PricingPricesSchema = PricingCreateSchema.pick({
  products: true
});
var PricingPricesFields = Object.keys(
  PricingPricesSchema.shape
);

// src/pages/price-lists/price-list-create/price-list-create.tsx
import { Children as Children2 } from "react";

// src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-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 useTranslation3 } from "react-i18next";

// src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsx
import { MagnifyingGlass, XMarkMini } from "@medusajs/icons";
import {
  Button,
  DatePicker,
  Divider,
  Heading,
  IconButton,
  Input,
  RadioGroup,
  Select,
  Text,
  Textarea,
  clx
} from "@medusajs/ui";
import { useFieldArray } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { jsx, jsxs } from "react/jsx-runtime";
var Root = () => {
  const { t } = useTranslation();
  const form = useTabbedForm();
  const direction = useDocumentDirection();
  const { fields, remove, append } = useFieldArray({
    control: form.control,
    name: "rules.customer_group_id",
    keyName: "cg_id"
  });
  const { setIsOpen } = useStackedModal();
  const handleAddCustomerGroup = (groups) => {
    const newIds = groups.map((group) => group.id);
    const fieldsToAdd = groups.filter(
      (group) => !fields.some((field) => field.id === group.id)
    );
    for (const field of fields) {
      if (!newIds.includes(field.id)) {
        remove(fields.indexOf(field));
      }
    }
    append(fieldsToAdd);
    setIsOpen("cg", false);
  };
  return /* @__PURE__ */ jsx("div", { className: "flex flex-1 flex-col items-center overflow-y-auto", "data-testid": "price-list-details-form", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-[720px] flex-col gap-y-8 px-8 py-16", children: [
    /* @__PURE__ */ jsxs("div", { "data-testid": "price-list-details-form-header", children: [
      /* @__PURE__ */ jsx(Heading, { "data-testid": "price-list-details-form-heading", children: t("priceLists.create.header") }),
      /* @__PURE__ */ jsx(Text, { size: "small", className: "text-ui-fg-subtle", "data-testid": "price-list-details-form-subheader", children: t("priceLists.create.subheader") })
    ] }),
    /* @__PURE__ */ jsx(
      Form.Field,
      {
        control: form.control,
        name: "type",
        render: ({ field: { onChange, ...rest } }) => {
          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "price-list-details-form-type-item", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
              /* @__PURE__ */ jsxs("div", { children: [
                /* @__PURE__ */ jsx(Form.Label, { "data-testid": "price-list-details-form-type-label", children: t("priceLists.fields.type.label") }),
                /* @__PURE__ */ jsx(Form.Hint, { "data-testid": "price-list-details-form-type-hint", children: t("priceLists.fields.type.hint") })
              ] }),
              /* @__PURE__ */ jsx(Form.Control, { "data-testid": "price-list-details-form-type-control", children: /* @__PURE__ */ jsxs(
                RadioGroup,
                {
                  dir: direction,
                  onValueChange: onChange,
                  ...rest,
                  className: "grid grid-cols-1 gap-4 md:grid-cols-2",
                  "data-testid": "price-list-details-form-type-radio-group",
                  children: [
                    /* @__PURE__ */ jsx(
                      RadioGroup.ChoiceBox,
                      {
                        value: "sale",
                        label: t("priceLists.fields.type.options.sale.label"),
                        description: t("priceLists.fields.type.options.sale.description"),
                        "data-testid": "price-list-details-form-type-option-sale"
                      }
                    ),
                    /* @__PURE__ */ jsx(
                      RadioGroup.ChoiceBox,
                      {
                        value: "override",
                        label: t("priceLists.fields.type.options.override.label"),
                        description: t("priceLists.fields.type.options.override.description"),
                        "data-testid": "price-list-details-form-type-option-override"
                      }
                    )
                  ]
                }
              ) })
            ] }),
            /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "price-list-details-form-type-error" })
          ] });
        }
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1  gap-4 md:grid-cols-2", children: [
        /* @__PURE__ */ jsx(
          Form.Field,
          {
            control: form.control,
            name: "title",
            render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "price-list-details-form-title-item", children: [
              /* @__PURE__ */ jsx(Form.Label, { "data-testid": "price-list-details-form-title-label", children: t("fields.title") }),
              /* @__PURE__ */ jsx(Form.Control, { "data-testid": "price-list-details-form-title-control", children: /* @__PURE__ */ jsx(Input, { ...field, "data-testid": "price-list-details-form-title-input" }) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "price-list-details-form-title-error" })
            ] })
          }
        ),
        /* @__PURE__ */ jsx(
          Form.Field,
          {
            control: form.control,
            name: "status",
            render: ({ field: { onChange, ref, ...field } }) => /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "price-list-details-form-status-item", children: [
              /* @__PURE__ */ jsx(Form.Label, { "data-testid": "price-list-details-form-status-label", children: t("priceLists.fields.status.label") }),
              /* @__PURE__ */ jsx(Form.Control, { "data-testid": "price-list-details-form-status-control", children: /* @__PURE__ */ jsxs(
                Select,
                {
                  dir: direction,
                  ...field,
                  onValueChange: onChange,
                  "data-testid": "price-list-details-form-status-select",
                  children: [
                    /* @__PURE__ */ jsx(Select.Trigger, { ref, "data-testid": "price-list-details-form-status-trigger", children: /* @__PURE__ */ jsx(Select.Value, { "data-testid": "price-list-details-form-status-value" }) }),
                    /* @__PURE__ */ jsxs(Select.Content, { "data-testid": "price-list-details-form-status-content", children: [
                      /* @__PURE__ */ jsx(Select.Item, { value: "active", "data-testid": "price-list-details-form-status-option-active", children: t("priceLists.fields.status.options.active") }),
                      /* @__PURE__ */ jsx(Select.Item, { value: "draft", "data-testid": "price-list-details-form-status-option-draft", children: t("priceLists.fields.status.options.draft") })
                    ] })
                  ]
                }
              ) }),
              /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "price-list-details-form-status-error" })
            ] })
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        Form.Field,
        {
          control: form.control,
          name: "description",
          render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "price-list-details-form-description-item", children: [
            /* @__PURE__ */ jsx(Form.Label, { "data-testid": "price-list-details-form-description-label", children: t("fields.description") }),
            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "price-list-details-form-description-control", children: /* @__PURE__ */ jsx(Textarea, { ...field, "data-testid": "price-list-details-form-description-input" }) }),
            /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "price-list-details-form-description-error" })
          ] })
        }
      )
    ] }),
    /* @__PURE__ */ jsx(Divider, {}),
    /* @__PURE__ */ jsx(
      Form.Field,
      {
        control: form.control,
        name: "starts_at",
        render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "price-list-details-form-starts-at-item", children: [
          /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 md:grid-cols-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
              /* @__PURE__ */ jsx(Form.Label, { optional: true, "data-testid": "price-list-details-form-starts-at-label", children: t("priceLists.fields.startsAt.label") }),
              /* @__PURE__ */ jsx(Form.Hint, { "data-testid": "price-list-details-form-starts-at-hint", children: t("priceLists.fields.startsAt.hint") })
            ] }),
            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "price-list-details-form-starts-at-control", children: /* @__PURE__ */ jsx(
              DatePicker,
              {
                granularity: "minute",
                shouldCloseOnSelect: false,
                ...field,
                "data-testid": "price-list-details-form-starts-at-input"
              }
            ) })
          ] }),
          /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "price-list-details-form-starts-at-error" })
        ] })
      }
    ),
    /* @__PURE__ */ jsx(Divider, {}),
    /* @__PURE__ */ jsx(
      Form.Field,
      {
        control: form.control,
        name: "ends_at",
        render: ({ field }) => /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "price-list-details-form-ends-at-item", children: [
          /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 md:grid-cols-2", children: [
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
              /* @__PURE__ */ jsx(Form.Label, { optional: true, "data-testid": "price-list-details-form-ends-at-label", children: t("priceLists.fields.endsAt.label") }),
              /* @__PURE__ */ jsx(Form.Hint, { "data-testid": "price-list-details-form-ends-at-hint", children: t("priceLists.fields.endsAt.hint") })
            ] }),
            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "price-list-details-form-ends-at-control", children: /* @__PURE__ */ jsx(
              DatePicker,
              {
                granularity: "minute",
                shouldCloseOnSelect: false,
                ...field,
                "data-testid": "price-list-details-form-ends-at-input"
              }
            ) })
          ] }),
          /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "price-list-details-form-ends-at-error" })
        ] })
      }
    ),
    /* @__PURE__ */ jsx(Divider, {}),
    /* @__PURE__ */ jsx(
      Form.Field,
      {
        control: form.control,
        name: "rules.customer_group_id",
        render: ({ field }) => {
          return /* @__PURE__ */ jsxs(Form.Item, { "data-testid": "price-list-details-form-customer-group-item", children: [
            /* @__PURE__ */ jsxs("div", { children: [
              /* @__PURE__ */ jsx(Form.Label, { optional: true, "data-testid": "price-list-details-form-customer-group-label", children: t("priceLists.fields.customerAvailability.label") }),
              /* @__PURE__ */ jsx(Form.Hint, { "data-testid": "price-list-details-form-customer-group-hint", children: t("priceLists.fields.customerAvailability.hint") })
            ] }),
            /* @__PURE__ */ jsx(Form.Control, { "data-testid": "price-list-details-form-customer-group-control", children: /* @__PURE__ */ jsxs(
              "div",
              {
                className: clx(
                  "bg-ui-bg-component shadow-elevation-card-rest transition-fg grid gap-1.5 rounded-xl py-1.5",
                  "aria-[invalid='true']:shadow-borders-error"
                ),
                role: "application",
                ref: field.ref,
                "data-testid": "price-list-details-form-customer-group-selector",
                children: [
                  /* @__PURE__ */ jsxs("div", { className: "text-ui-fg-subtle grid gap-1.5 px-1.5 md:grid-cols-2", children: [
                    /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5", children: t("priceLists.fields.customerAvailability.attribute") }),
                    /* @__PURE__ */ jsx("div", { className: "bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5", children: t("operators.in") })
                  ] }),
                  /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1.5 px-1.5", children: /* @__PURE__ */ jsxs(StackedFocusModal, { id: "cg", children: [
                    /* @__PURE__ */ jsx(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsxs(
                      "button",
                      {
                        type: "button",
                        className: "bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover shadow-borders-base txt-compact-small text-ui-fg-muted transition-fg focus-visible:shadow-borders-interactive-with-active flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5 outline-none",
                        "data-testid": "price-list-details-form-customer-group-search-button",
                        children: [
                          /* @__PURE__ */ jsx(MagnifyingGlass, {}),
                          t("priceLists.fields.customerAvailability.placeholder")
                        ]
                      }
                    ) }),
                    /* @__PURE__ */ jsx(StackedFocusModal.Trigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { variant: "secondary", "data-testid": "price-list-details-form-customer-group-browse-button", children: t("actions.browse") }) }),
                    /* @__PURE__ */ jsxs(StackedFocusModal.Content, { children: [
                      /* @__PURE__ */ jsx(StackedFocusModal.Header, {}),
                      /* @__PURE__ */ jsx(
                        PriceListCustomerGroupRuleForm,
                        {
                          state: fields,
                          setState: handleAddCustomerGroup,
                          type: "focus"
                        }
                      )
                    ] })
                  ] }) }),
                  fields.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-y-1.5", "data-testid": "price-list-details-form-customer-group-selected", children: [
                    /* @__PURE__ */ jsx(Divider, { variant: "dashed" }),
                    /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-y-1.5 px-1.5", children: fields.map((field2, index) => {
                      return /* @__PURE__ */ jsxs(
                        "div",
                        {
                          className: "bg-ui-bg-field-component shadow-borders-base flex items-center justify-between gap-2 rounded-md px-2 py-0.5",
                          "data-testid": `price-list-details-form-customer-group-selected-${field2.id}`,
                          children: [
                            /* @__PURE__ */ jsx(Text, { size: "small", leading: "compact", "data-testid": `price-list-details-form-customer-group-selected-${field2.id}-name`, children: field2.name }),
                            /* @__PURE__ */ jsx(
                              IconButton,
                              {
                                size: "small",
                                variant: "transparent",
                                type: "button",
                                onClick: () => remove(index),
                                "data-testid": `price-list-details-form-customer-group-selected-${field2.id}-remove-button`,
                                children: /* @__PURE__ */ jsx(XMarkMini, {})
                              }
                            )
                          ]
                        },
                        field2.cg_id
                      );
                    }) })
                  ] }) : null
                ]
              }
            ) }),
            /* @__PURE__ */ jsx(Form.ErrorMessage, { "data-testid": "price-list-details-form-customer-group-error" })
          ] });
        }
      }
    )
  ] }) });
};
Root._tabMeta = defineTabMeta({
  id: "detail",
  labelKey: "priceLists.create.tabs.details",
  validationFields: ["type", "title", "description", "starts_at", "ends_at"]
});
var PriceListDetailsForm = Root;

// src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsx
import { useEffect } from "react";
import { useWatch } from "react-hook-form";
import { jsx as jsx2 } from "react/jsx-runtime";
var Root2 = ({
  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 { setCloseOnEscape } = useRouteModal();
  const { setValue } = form;
  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__ */ jsx2("div", { className: "flex size-full flex-col divide-y overflow-hidden", children: /* @__PURE__ */ jsx2(
    DataGrid,
    {
      isLoading,
      columns,
      data: products,
      getSubRows: (row) => {
        if (isProductRow(row) && row.variants) {
          return row.variants;
        }
      },
      state: form,
      onEditingChange: (editing) => setCloseOnEscape(!editing)
    }
  ) });
};
Root2._tabMeta = defineTabMeta({
  id: "price",
  labelKey: "priceLists.create.tabs.prices",
  validationFields: ["products"]
});
var PriceListPricesForm = Root2;

// src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsx
import { Checkbox } 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 as useTranslation2 } from "react-i18next";
import { jsx as jsx3 } 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 Root3 = () => {
  const { t } = useTranslation2();
  const form = useTabbedForm();
  const { control, setValue } = form;
  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;
    },
    getRowId: (row) => row.id,
    rowSelection: {
      state: rowSelection,
      updater
    },
    pageSize: PAGE_SIZE,
    prefix: PREFIX
  });
  if (isError) {
    throw error;
  }
  return /* @__PURE__ */ jsx3("div", { className: "flex size-full flex-col", children: /* @__PURE__ */ jsx3(
    _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,
      noRecords: {
        message: t("priceLists.create.products.list.noRecordsMessage")
      }
    }
  ) });
};
var columnHelper = createColumnHelper();
var useColumns = () => {
  const base = useProductTableColumns();
  return useMemo(
    () => [
      columnHelper.display({
        id: "select",
        header: ({ table }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: table.getIsSomePageRowsSelected() ? "indeterminate" : table.getIsAllPageRowsSelected(),
              onCheckedChange: (value) => table.toggleAllPageRowsSelected(!!value)
            }
          );
        },
        cell: ({ row }) => {
          return /* @__PURE__ */ jsx3(
            Checkbox,
            {
              checked: row.getIsSelected(),
              disabled: !row.getCanSelect(),
              onCheckedChange: (value) => row.toggleSelected(!!value),
              onClick: (e) => {
                e.stopPropagation();
              }
            }
          );
        }
      }),
      ...base
    ],
    [base]
  );
};
Root3._tabMeta = defineTabMeta({
  id: "product",
  labelKey: "priceLists.create.tabs.products",
  validationFields: ["product_ids"]
});
var PriceListProductsForm = Root3;

// src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsx
import { jsx as jsx4 } from "react/jsx-runtime";
var PriceListCreateForm = ({
  regions,
  currencies,
  pricePreferences,
  children,
  schema,
  defaultValues: extraDefaults
}) => {
  const { t } = useTranslation3();
  const { handleSuccess } = useRouteModal();
  const form = useForm({
    defaultValues: {
      type: "sale",
      status: "active",
      title: "",
      description: "",
      starts_at: null,
      ends_at: null,
      product_ids: [],
      products: {},
      rules: {
        customer_group_id: []
      },
      ...extraDefaults
    },
    resolver: zodResolver(schema ?? PricingCreateSchema)
  });
  const { mutateAsync, isPending } = useCreatePriceList();
  const handleSubmit = form.handleSubmit(async (data) => {
    const { rules, products } = data;
    const rulesPayload = rules?.customer_group_id?.length ? { "customer.groups.id": rules.customer_group_id.map((cg) => cg.id) } : void 0;
    const prices = exctractPricesFromProducts(products, regions);
    await mutateAsync(
      {
        title: data.title,
        type: data.type,
        status: data.status,
        description: data.description,
        starts_at: data.starts_at ? data.starts_at.toISOString() : null,
        ends_at: data.ends_at ? data.ends_at.toISOString() : null,
        rules: rulesPayload,
        prices
      },
      {
        onSuccess: ({ price_list }) => {
          toast.success(
            t("priceLists.create.successToast", {
              title: price_list.title
            })
          );
          handleSuccess(`../${price_list.id}`);
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const defaultTabs = useMemo2(
    () => [
      /* @__PURE__ */ jsx4(PriceListDetailsForm, {}, "detail"),
      /* @__PURE__ */ jsx4(PriceListProductsForm, {}, "product"),
      /* @__PURE__ */ jsx4(
        PriceListPricesForm,
        {
          currencies,
          regions,
          pricePreferences
        },
        "price"
      )
    ],
    [currencies, regions, pricePreferences]
  );
  const hasCustomChildren = Children.count(children) > 0;
  return /* @__PURE__ */ jsx4(
    TabbedForm,
    {
      form,
      onSubmit: handleSubmit,
      isLoading: isPending,
      children: hasCustomChildren ? children : defaultTabs
    }
  );
};

// src/pages/price-lists/price-list-create/price-list-create.tsx
import { jsx as jsx5 } from "react/jsx-runtime";
var Root4 = ({ children }) => {
  const { isReady, regions, currencies, pricePreferences } = usePriceListCurrencyData();
  return /* @__PURE__ */ jsx5(RouteFocusModal, { children: isReady && (Children2.count(children) > 0 ? children : /* @__PURE__ */ jsx5(
    PriceListCreateForm,
    {
      regions,
      currencies,
      pricePreferences
    }
  )) });
};
var PriceListCreatePage = Object.assign(Root4, {
  Form: PriceListCreateForm,
  DetailsTab: PriceListDetailsForm,
  ProductsTab: PriceListProductsForm,
  PricesTab: PriceListPricesForm,
  Tab: TabbedForm.Tab
});
var PriceListCreate = Root4;

export {
  PricingCreateSchema,
  PriceListCreatePage,
  PriceListCreate
};
