import BigNumber from 'bignumber.js'
import React, { useEffect, useCallback, useMemo, useState, useRef } from 'react'
import { Route, useRouteMatch, useLocation } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import boardsConfig from 'config/constants/boards'
import tokens from 'config/constants/tokens'
import { getAddress, getBoardAddress } from 'utils/addressHelpers'
import { getBalanceAmount } from 'utils/formatBalance'
import boardABI from 'config/abi/board.json'
import erc20ABI from 'config/abi/erc20.json'
import multicall from 'utils/multicall'
import { useWeb3React } from '@web3-react/core'
import Balance from 'components/Balance'
import { Image, Heading, RowType, Toggle, Text } from '@pancakeswap/uikit'
import styled from 'styled-components'
import FlexLayout from 'components/Layout/Flex'
import Page from 'components/Layout/Page'
import { useBoards } from 'state/hooks'
import useRefresh from 'hooks/useRefresh'
import { fetchBoardUserDataAsync, fetchBoardsPublicDataAsync } from 'state/actions'
import { fetchBoardUserInfo } from 'state/boards/fetchBoardsUser'
import { useTranslation } from 'contexts/Localization'
import BoardCard from './components/BoardCard/BoardCard'
import HeaderItem from './components/HeaderItem'

const Header = styled.div`
  padding: 32px 0px;
  padding-left: 16px;
  padding-right: 16px;
  text-align: center;

  ${({ theme }) => theme.mediaQueries.sm} {
    padding-left: 24px;
    padding-right: 24px;
  }
`
const SecondText = styled(Text)`
  white-space: break-spaces;
`
const FlexLayoutMain = styled(FlexLayout)`
  margin-top: 20px;
`
const Boards: React.FC = () => {
  const { t } = useTranslation()
  const boardsList = useBoards()
  const [query, setQuery] = useState('')
  const { account } = useWeb3React()

  const dispatch = useDispatch()
  const { fastRefresh } = useRefresh()
  // 资金池总额
  const [totalAmount, setTotalAmount] = useState(0)
  // 分红总额
  const [shareOutBonus, setShareOutBonus] = useState(0)

  const [boardNum, setBoardNum] = useState(0)
  const [holderNum, setHolder] = useState(0)

  // 获取分红总额
  const fetchBoardShares = async () => {
    const boardsData = await Promise.all(
      boardsConfig.map(async (boardConfig) => {
        const [boardPoolInfo] = await multicall(boardConfig.abi, [
          {
            address: getAddress(boardConfig.contractAddress),
            name: '_poolInfo',
          },
        ])
        const [waitWithdrawAmount] = await multicall(erc20ABI, [
          {
            address: getAddress(boardConfig.tokenAddresses),
            name: 'balanceOf',
            params: [getAddress(boardConfig.contractRewardAddress)],
          },
        ])
        return {
          pid: boardConfig.pid,
          totalAmount: getBalanceAmount(new BigNumber(boardPoolInfo.totalAmount._hex)).toNumber(),
          num: new BigNumber(boardPoolInfo?.num?._hex).toNumber(),
          waitWithdrawAmount: getBalanceAmount(new BigNumber(waitWithdrawAmount.balance._hex)).toNumber(),
        }
      }),
    )
    let total = 0
    let waitWithdrawAmountValue = 0
    boardsData.forEach((item) => {
      total += item.totalAmount
      waitWithdrawAmountValue += item.waitWithdrawAmount
      if (item.pid === 1) {
        setBoardNum(item.num)
      } else if (item.pid === 2) {
        setHolder(item.waitWithdrawAmount)
      }
    })
    setTotalAmount(total)
    setShareOutBonus(waitWithdrawAmountValue)
  }
  useEffect(() => {
    dispatch(fetchBoardsPublicDataAsync())
    fetchBoardShares()
    if (account) {
      dispatch(fetchBoardUserDataAsync(account))
    }
  }, [account, dispatch, fastRefresh])

  const renderContent = (): JSX.Element => {
    return (
      <div>
        <FlexLayout>
          {boardsList.map((board) => (
            <BoardCard key={board.pid} board={board} account={account} removed />
          ))}
        </FlexLayout>
      </div>
    )
  }

  return (
    <Page>
      <Header>
        <Heading as="h1" size="xl" color="text" mb="10px" mt="10px">
          {t('Total capital pool')}
        </Heading>
        <Balance lineHeight="1" fontSize="32px" decimals={0} value={Number(totalAmount)} />
        <FlexLayoutMain>
          <HeaderItem title={t('The total amount of dividends')} price={shareOutBonus} />
          {/* <HeaderItem title={t('Pending dividend')} price={1.0} /> */}
          <HeaderItem title={t('Number of boards')} price={boardNum} />
          <HeaderItem title={t('Number of holders')} price={holderNum} />
        </FlexLayoutMain>
      </Header>
      {renderContent()}
    </Page>
  )
}

export default Boards
