import { useRequest } from 'ahooks';
import { CircularProgress, Typography } from '@mui/material';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import type { TProductExpanded } from '@blocklet/payment-types';
import { useMemo } from 'react';
import Toast from '@arcblock/ux/lib/Toast';
import { Box } from '@mui/system';
import api from '../libs/api';
import { formatError, formatTotalPrice } from '../libs/util';
import type { PricingRenderProps } from '../types';

const fetchProduct = (productId: string): Promise<TProductExpanded> => {
  return api.get(`/api/products/${productId}`).then((res: any) => res?.data);
};

export type PricingItemProps = {
  productId: string;
  quantity: number;
  priceId: string | undefined;
  children?: (pricing: PricingRenderProps, product?: TProductExpanded | undefined) => React.ReactNode;
};

function PricingItem({ productId, quantity, children = undefined, priceId }: PricingItemProps) {
  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: any) => {
      Toast.error(formatError(err));
    },
  });

  const pricing: PricingRenderProps = useMemo(
    () =>
      formatTotalPrice({
        product: productInfo!,
        quantity,
        priceId,
        locale,
      }),
    [productInfo, quantity, priceId, locale]
  );
  if (loading) {
    return <CircularProgress />;
  }
  return <Box>{children ? children(pricing, productInfo) : <Typography>{pricing?.totalPrice}</Typography>}</Box>;
}

export default PricingItem;
