import React, { useMemo } from 'react'
import dayjs from 'dayjs'
import styled from 'styled-components'
import BigNumber from 'bignumber.js'
import { Button, Flex, Heading, IconButton, AddIcon, MinusIcon, useModal } from '@pancakeswap/uikit'
import { getBalanceNumber } from 'utils/formatBalance'
import { useBoardsFromPid } from 'state/hooks'
import { useTranslation } from 'contexts/Localization'
import useToast from 'hooks/useToast'
import DepositModal from '../DepositModal'
import useStakeBoard from '../../hooks/useStakeBoard'
import useUnstakeBoard, { useUnstakeForceBoard } from '../../hooks/useUnstakeBoard'
import WithdrawModal from '../WithdrawModal'

interface NodeCardActionsProps {
  stakedBalance?: BigNumber
  tokenBalance?: BigNumber
  tokenName?: string
  pid?: number
}

const IconButtonWrapper = styled.div`
  display: flex;
  svg {
    width: 20px;
  }
`

const StakeAction: React.FC<NodeCardActionsProps> = ({ stakedBalance, tokenBalance, tokenName, pid }) => {
  const { t } = useTranslation()
  const { toastWarning } = useToast()
  const { onStake } = useStakeBoard(pid)
  const { onUnstake } = useUnstakeBoard(pid)
  const { onUnstake: onUnstakeForce } = useUnstakeForceBoard(pid)
  const { tokenDecimals = 18, minStakeAmount, userData } = useBoardsFromPid(pid)
  const rawStakedBalance = getBalanceNumber(stakedBalance, tokenDecimals, 8)
  const minStakedAmount = useMemo(() => {
    const minAmount = minStakeAmount - getBalanceNumber(userData.stakedBalance, tokenDecimals)
    return minAmount < 0 ? new BigNumber(0) : new BigNumber(minAmount)
  }, [userData, minStakeAmount, tokenDecimals])
  const [onPresentDeposit] = useModal(
    <DepositModal
      max={tokenBalance}
      tokenDecimals={tokenDecimals}
      min={minStakedAmount}
      onConfirm={onStake}
      tokenName={tokenName}
    />,
  )
  const [onPresentWithdraw] = useModal(
    <WithdrawModal max={stakedBalance} tokenDecimals={tokenDecimals} onConfirm={onUnstake} tokenName={tokenName} />,
  )
  const handleUnstake = () => {
    const unlockTime = userData.unlockTime * 1000
    if (unlockTime > new Date().getTime()) {
      onUnstakeForce()
    } else {
      onUnstake()
    }
  }
  const renderStakingButtons = () => {
    return rawStakedBalance === 0 ? (
      <Button onClick={onPresentDeposit}>{t(`pledge`)}</Button>
    ) : (
      <IconButtonWrapper>
        {userData.stakedBalance > 0 ? (
          <IconButton variant="tertiary" onClick={handleUnstake}>
            <MinusIcon color="primary" />
          </IconButton>
        ) : (
          <IconButton variant="tertiary" onClick={onPresentDeposit} ml="6px">
            <AddIcon color="primary" />
          </IconButton>
        )}
      </IconButtonWrapper>
    )
  }

  return (
    <Flex justifyContent="space-between" alignItems="center">
      <Heading color={rawStakedBalance === 0 ? 'textDisabled' : 'text'}>{rawStakedBalance}</Heading>
      {renderStakingButtons()}
    </Flex>
  )
}

export default StakeAction
