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

type AccountBalanceProps = Omit<BlockProps, "children">

export default function AccountBalance(props: AccountBalanceProps) {
  const { overrides, ...restProps } = props
  const [, theme] = useStyletron()
  const { nativeBalanceRefetchInterval } = usePassportContext()

  const {
    data: tokensBalancesData,
    isError: isTokensBalancesError,
    isPending: isTokensBalancesDataPending,
  } = useTokensBalances({
    queryOptions: {
      staleTime: nativeBalanceRefetchInterval,
      refetchInterval: nativeBalanceRefetchInterval,
    },
  })
  const {
    data: borrowData,
    isError: isBorrowDataError,
    isPending: isBorrowDataPending,
  } = useBorrowData()

  if (isTokensBalancesDataPending || isBorrowDataPending) {
    return <ListingItem isLoading overrides={overrides} />
  }

  if (isTokensBalancesError || isBorrowDataError) {
    return (
      <AccountError
        padding={`${theme.sizing.scale500} ${theme.sizing.scale800}`}
        topic="account balance"
        overrides={overrides}
      />
    )
  }

  const totalBalanceInUsd = Object.values(tokensBalancesData).reduce(
    (acc, tokenBalance) => acc + tokenBalance.usd.value,
    0n,
  )

  const totalBalanceNumber = Number(
    formatUnits(totalBalanceInUsd, CONVERSION_RATE_DECIMALS),
  )

  const totalDebtNumber = Number(borrowData.debtInUsd.formatted)

  return (
    <ListingItem
      label="Total assets"
      value={totalBalanceNumber}
      subLabel="Total liabilities"
      subValue={totalDebtNumber}
      overrides={overrides}
      {...restProps}
    />
  )
}
