import React from "react"
import { BitcoinCircle, BlockProps } from "@mezo-org/mezo-clay"
import ListingItem from "../ListingItem"
import { getAsset } from "../../../utils/assets"
import { useBorrowData } from "../../../hooks/useBorrowData"
import { useTokensBalances } from "../../../hooks/useTokensBalances"
import AccountError from "./AccountError"
import { usePassportContext } from "../../../hooks/usePassportContext"

type AccountBTCListingProps = Omit<BlockProps, "children">

export default function AccountBTCListing(props: AccountBTCListingProps) {
  const { nativeBalanceRefetchInterval } = usePassportContext()

  const {
    data: borrowData,
    isError: isBorrowDataError,
    isPending: isBorrowDataPending,
  } = useBorrowData()

  const {
    data: tokensBalancesData,
    isError: isTokensBalancesError,
    isPending: isTokensBalancesPending,
  } = useTokensBalances({
    queryOptions: {
      staleTime: nativeBalanceRefetchInterval,
      refetchInterval: nativeBalanceRefetchInterval,
    },
  })

  if (isTokensBalancesPending || isBorrowDataPending) {
    return <ListingItem isLoading />
  }

  if (isTokensBalancesError || isBorrowDataError) {
    return <AccountError topic="Bitcoin balance" />
  }

  const btcBalance = Number(tokensBalancesData.BTC.usd.formatted)
  const lockedCollateral = Number(borrowData.collateral.usd.formatted)

  return (
    <ListingItem
      icon={<BitcoinCircle />}
      label={getAsset("BTC").name}
      value={btcBalance}
      subLabel="Locked collateral"
      subValue={lockedCollateral}
      {...props}
    />
  )
}
