import { jsx } from "react/jsx-runtime";
import { useRequest } from "ahooks";
import { CircularProgress, Typography } from "@mui/material";
import { useLocaleContext } from "@arcblock/ux/lib/Locale/context";
import { useMemo } from "react";
import Toast from "@arcblock/ux/lib/Toast";
import { Box } from "@mui/system";
import api from "../libs/api.js";
import { formatError, formatTotalPrice } from "../libs/util.js";
const fetchProduct = (productId) => {
  return api.get(`/api/products/${productId}`).then((res) => res?.data);
};
function PricingItem({ productId, quantity, children = void 0, priceId }) {
  const { locale } = useLocaleContext();
  const { data: productInfo, loading = false } = useRequest(() => fetchProduct(productId), {
    refreshDeps: [productId],
    onSuccess: (res) => {
      if (!res) {
        Toast.error(formatError(new Error("Product not found")));
      }
    },
    onError: (err) => {
      Toast.error(formatError(err));
    }
  });
  const pricing = useMemo(
    () => formatTotalPrice({
      product: productInfo,
      quantity,
      priceId,
      locale
    }),
    [productInfo, quantity, priceId, locale]
  );
  if (loading) {
    return /* @__PURE__ */ jsx(CircularProgress, {});
  }
  return /* @__PURE__ */ jsx(Box, { children: children ? children(pricing, productInfo) : /* @__PURE__ */ jsx(Typography, { children: pricing?.totalPrice }) });
}
export default PricingItem;
