import {
  PriceListUpdateProductsSchema,
  usePriceListGridColumns
} from "./chunk-X6ZQMFCT.js";
import {
  isProductRow
} from "./chunk-BNOKKKUU.js";
import {
  DataGrid
} from "./chunk-5FBQOAXU.js";
import {
  castNumber
} from "./chunk-SMQT3ZNO.js";
import {
  KeyboundForm
} from "./chunk-SITRHMZZ.js";
import {
  RouteFocusModal,
  useRouteModal
} from "./chunk-GDWBOQI5.js";
import {
  useBatchPriceListPrices
} from "./chunk-P7UBW2EI.js";

// src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/price-list-prices-edit-form.tsx
import { zodResolver } from "@hookform/resolvers/zod";
import { Button, toast } from "@medusajs/ui";
import { useRef } from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { z } from "zod";
import { jsx, jsxs } from "react/jsx-runtime";
var PricingProductPricesSchema = z.object({
  products: PriceListUpdateProductsSchema
});
var PriceListPricesEditForm = ({
  priceList,
  products,
  regions,
  currencies,
  pricePreferences
}) => {
  const { t } = useTranslation();
  const { handleSuccess, setCloseOnEscape } = useRouteModal();
  const initialValue = useRef(initRecord(priceList, products));
  const form = useForm({
    defaultValues: {
      products: initialValue.current
    },
    resolver: zodResolver(PricingProductPricesSchema)
  });
  const { mutateAsync, isPending } = useBatchPriceListPrices(priceList.id);
  const handleSubmit = form.handleSubmit(async (values) => {
    const { products: products2 } = values;
    const { pricesToDelete, pricesToCreate, pricesToUpdate } = sortPrices(
      products2,
      initialValue.current,
      regions
    );
    mutateAsync(
      {
        delete: pricesToDelete,
        update: pricesToUpdate,
        create: pricesToCreate
      },
      {
        onSuccess: () => {
          toast.success(t("priceLists.products.edit.successToast"));
          handleSuccess();
        },
        onError: (error) => {
          toast.error(error.message);
        }
      }
    );
  });
  const columns = usePriceListGridColumns({
    currencies,
    regions,
    pricePreferences
  });
  return /* @__PURE__ */ jsx(RouteFocusModal.Form, { form, children: /* @__PURE__ */ jsxs(KeyboundForm, { onSubmit: handleSubmit, className: "flex size-full flex-col", children: [
    /* @__PURE__ */ jsx(RouteFocusModal.Header, {}),
    /* @__PURE__ */ jsx(RouteFocusModal.Body, { className: "flex flex-col overflow-hidden", children: /* @__PURE__ */ jsx(
      DataGrid,
      {
        columns,
        data: products,
        getSubRows: (row) => {
          if (isProductRow(row) && row.variants) {
            return row.variants;
          }
        },
        state: form,
        onEditingChange: (editing) => setCloseOnEscape(!editing)
      }
    ) }),
    /* @__PURE__ */ jsx(RouteFocusModal.Footer, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-x-2", 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: isPending, children: t("actions.save") })
    ] }) })
  ] }) });
};
function initRecord(priceList, products) {
  const record = {};
  const variantPrices = priceList.prices?.reduce((variants, price) => {
    const variantObject = variants[price.variant_id] || {};
    const isRegionPrice = !!price.rules?.region_id;
    if (isRegionPrice) {
      const regionId = price.rules.region_id;
      variantObject.region_prices = {
        ...variantObject.region_prices,
        [regionId]: {
          amount: price.amount.toString(),
          id: price.id
        }
      };
    } else {
      variantObject.currency_prices = {
        ...variantObject.currency_prices,
        [price.currency_code]: {
          amount: price.amount.toString(),
          id: price.id
        }
      };
    }
    variants[price.variant_id] = variantObject;
    return variants;
  }, {});
  for (const product of products) {
    record[product.id] = {
      variants: product.variants?.reduce((variants, variant) => {
        const prices = variantPrices[variant.id] || {};
        variants[variant.id] = prices;
        return variants;
      }, {}) || {}
    };
  }
  return record;
}
function convertToPriceArray(data, regions) {
  const prices = [];
  const regionCurrencyMap = regions.reduce(
    (map, region) => {
      map[region.id] = region.currency_code;
      return map;
    },
    {}
  );
  for (const [_productId, product] of Object.entries(data || {})) {
    const { variants } = product || {};
    for (const [variantId, variant] of Object.entries(variants || {})) {
      const { currency_prices: currencyPrices, region_prices: regionPrices } = variant || {};
      for (const [currencyCode, currencyPrice] of Object.entries(
        currencyPrices || {}
      )) {
        if (currencyPrice?.amount !== "" && typeof currencyPrice?.amount !== "undefined") {
          prices.push({
            variantId,
            currencyCode,
            amount: castNumber(currencyPrice.amount),
            id: currencyPrice.id
          });
        }
      }
      for (const [regionId, regionPrice] of Object.entries(
        regionPrices || {}
      )) {
        if (regionPrice?.amount !== "" && typeof regionPrice?.amount !== "undefined") {
          prices.push({
            variantId,
            regionId,
            currencyCode: regionCurrencyMap[regionId],
            amount: castNumber(regionPrice.amount),
            id: regionPrice.id
          });
        }
      }
    }
  }
  return prices;
}
function createMapKey(obj) {
  return `${obj.variantId}-${obj.currencyCode}-${obj.regionId || "none"}-${obj.id || "none"}`;
}
function comparePrices(initialPrices, newPrices) {
  const pricesToUpdate = [];
  const pricesToCreate = [];
  const pricesToDelete = [];
  const initialPriceMap = initialPrices.reduce(
    (map, price) => {
      map[createMapKey(price)] = price;
      return map;
    },
    {}
  );
  const newPriceMap = newPrices.reduce(
    (map, price) => {
      map[createMapKey(price)] = price;
      return map;
    },
    {}
  );
  const keys = /* @__PURE__ */ new Set([
    ...Object.keys(initialPriceMap),
    ...Object.keys(newPriceMap)
  ]);
  for (const key of keys) {
    const initialPrice = initialPriceMap[key];
    const newPrice = newPriceMap[key];
    if (initialPrice && newPrice) {
      if (isNaN(newPrice.amount) && newPrice.id) {
        pricesToDelete.push(newPrice.id);
      }
      if (initialPrice.amount !== newPrice.amount && newPrice.id) {
        pricesToUpdate.push({
          id: newPrice.id,
          variant_id: newPrice.variantId,
          currency_code: newPrice.currencyCode,
          rules: newPrice.regionId ? { region_id: newPrice.regionId } : void 0,
          amount: newPrice.amount
        });
      }
    }
    if (!initialPrice && newPrice) {
      pricesToCreate.push({
        variant_id: newPrice.variantId,
        currency_code: newPrice.currencyCode,
        rules: newPrice.regionId ? { region_id: newPrice.regionId } : void 0,
        amount: newPrice.amount
      });
    }
    if (initialPrice && !newPrice && initialPrice.id) {
      pricesToDelete.push(initialPrice.id);
    }
  }
  return { pricesToDelete, pricesToCreate, pricesToUpdate };
}
function sortPrices(data, initialValue, regions) {
  const initialPrices = convertToPriceArray(initialValue, regions);
  const newPrices = convertToPriceArray(data, regions);
  return comparePrices(initialPrices, newPrices);
}

export {
  PriceListPricesEditForm
};
