/* eslint-disable react/prop-types */
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import { formatBNStr, usePaymentContext } from '@blocklet/payment-react';
import type { GroupedBN } from '@blocklet/payment-types';
import { Avatar, Stack, Typography } from '@mui/material';
import flatten from 'lodash/flatten';
import isEmpty from 'lodash/isEmpty';

type Props = {
  data?: GroupedBN;
  showLogo?: boolean;
};

export default function BalanceList(rawProps: Props) {
  const props = Object.assign(
    {
      data: {},
      showLogo: false,
    },
    rawProps
  );
  const { t } = useLocaleContext();
  const { settings } = usePaymentContext();
  const currencies = flatten(settings.paymentMethods.map((method) => method.payment_currencies));

  if (isEmpty(props.data)) {
    return (
      <Typography
        sx={{
          color: 'text.secondary',
        }}>
        {t('common.none')}
      </Typography>
    );
  }

  return (
    <Stack
      direction="column"
      sx={{
        alignItems: 'flex-start',
        width: '100%',
      }}>
      {Object.entries(props.data).map(([currencyId, amount]) => {
        const currency = currencies.find((c) => c.id === currencyId);
        if (!currency) {
          return null;
        }
        return (
          <Stack
            key={currencyId}
            direction="row"
            spacing={1}
            sx={{
              alignItems: 'center',
              width: '100%',
              maxWidth: '280px',
            }}>
            {props?.showLogo && (
              <Avatar src={currency.logo} alt={currency.symbol} style={{ width: '18px', height: '18px' }} />
            )}
            <Typography
              sx={{
                color: 'text.secondary',
                width: '32px',
                minWidth: 100,
              }}>
              {currency.symbol}
            </Typography>
            <Typography
              sx={{
                color: 'text.primary',
                flex: 1,
                textAlign: 'right',
              }}>
              {formatBNStr(amount, currency.decimal, 6, false)}
            </Typography>
          </Stack>
        );
      })}
    </Stack>
  );
}
