import React from "react"
import {
  useStyletron,
  CoinsStacked02,
  mergeOverrides,
  BlockProps,
} from "@mezo-org/mezo-clay"
import { formatUnits } from "viem"
import ListingItem from "../ListingItem"
import { useTokensBalances } from "../../../hooks/useTokensBalances"
import AccountError from "./AccountError"
import { CONVERSION_RATE_DECIMALS } from "../../../hooks/useAssetsConversionRates"

type AccountOtherAssetsProps = {
  onClick?: () => void
} & Omit<BlockProps, "children">

export default function AccountOtherAssets(props: AccountOtherAssetsProps) {
  const { onClick, overrides, ...restProps } = props

  const [, theme] = useStyletron()

  const {
    data: tokensBalancesData,
    isPending: isTokensBalancesPending,
    isError: isTokensBalancesError,
  } = useTokensBalances()

  if (isTokensBalancesPending) {
    return <ListingItem isLoading overrides={overrides} />
  }

  if (isTokensBalancesError) {
    return (
      <AccountError
        topic="other assets"
        paddingTop={theme.sizing.scale100}
        paddingBottom={theme.sizing.scale100}
        overrides={overrides}
      />
    )
  }

  const otherAssets = Object.values(tokensBalancesData)
    .filter((asset) => !["BTC", "MUSD", "MEZO"].includes(asset.symbol))
    .filter((asset) => asset.value > 0n)

  const assetsCount = otherAssets.length
  const totalAssetsInUsd = Number(
    formatUnits(
      otherAssets.reduce((total, asset) => total + asset.usd.value, 0n),
      CONVERSION_RATE_DECIMALS,
    ),
  )

  let label = "No other assets"
  if (assetsCount === 1) label = "1 more asset"
  if (assetsCount > 1) label = `${assetsCount} more assets`

  return (
    <ListingItem
      icon={<CoinsStacked02 color={theme.colors.contentPrimary} />}
      label={label}
      value={totalAssetsInUsd}
      overrides={mergeOverrides(
        {
          Block: {
            props: {
              $as: "button",
              onClick,
            },
            style: {
              borderWidth: 0,
              cursor: "pointer",
              backgroundColor: "transparent",
              minHeight: "56px",
            },
          },
        },
        overrides,
      )}
      {...restProps}
    />
  )
}
