import React, { useMemo, useEffect, useState } 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 { Boards } from 'state/types'
import { useBoardsFromPid } from 'state/hooks'
import { useTranslation } from 'contexts/Localization'
import { getBaseConfig } from 'services/board'
import useToast from 'hooks/useToast'
import DepositModal from '../DepositModal'
import AffirmModal from '../AffirmModal'

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
  board?: Boards
}

const IconButtonWrapper = styled.div`
  width: 100%;
  svg {
    width: 20px;
  }
`
const IconButtonDiv = styled(IconButton)`
  width: 100%;
  padding: 0 10px;
`

const StakeAction: React.FC<NodeCardActionsProps> = ({ stakedBalance, tokenBalance, tokenName, pid, board }) => {
  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 [unlockTimeTxt, setUnlockTimeTxt] = useState('')

  const getLockUpTime = async () => {
    const times = await getBaseConfig()
    formatSeconds(Number(times))
  }

  const formatSeconds = (value: number) => {
    const second = value
    //  分
    let minute = 0
    //  如果秒数大于60，将秒数转换成整数
    if (second > 60) {
      // 获取分钟，除以60取整数，得到整数分钟
      minute = second / 60
      // 获取秒数，秒数取佘，得到整数秒数
      const ss = second % 60
      // 如果分钟大于60，将分钟转换成小时
      if (minute > 60) {
        // 获取小时，获取分钟除以60，得到整数小时
        const hh = minute / 60
        // 获取小时后取佘的分，获取分钟除以60取佘的分
        const mm = minute % 60
        setUnlockTimeTxt(`${parseInt(hh.toString())}:${parseInt(mm.toString())}:${parseInt(ss.toString())}`)
      }
    } else {
      setUnlockTimeTxt(second.toString())
    }
  }
  useEffect(() => {
    getLockUpTime()
  }, [])
  const [onPresentDeposit] = useModal(
    <DepositModal
      board={board}
      time={unlockTimeTxt}
      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 [onPresentAffirm] = useModal(
    <AffirmModal
      title={
        board.pid === 1
          ? board.userData?.unlockTime * 1000 <= new Date().getTime()
            ? t('Cancel the pledge')
            : t('Forced to cancel')
          : t('Cancel the pledge')
      }
      content={
        board.pid === 1
          ? board.userData?.unlockTime * 1000 <= new Date().getTime()
            ? t('Cancel the pledge')
            : t('Earnings will be cleared after forced cancellation. Confirm cancellation')
          : t('Cancel the pledge')
      }
      handSubmit={handleUnstake}
    />,
  )
  const renderStakingButtons = () => {
    return rawStakedBalance === 0 ? (
      <Button width="100%" onClick={onPresentDeposit}>
        {t(`pledge`)}
      </Button>
    ) : (
      <IconButtonWrapper>
        {userData.stakedBalance > 0 ? (
          // <IconButtonDiv variant="tertiary" onClick={handleUnstake}>
          <IconButtonDiv variant="tertiary" onClick={onPresentAffirm}>
            {board.pid === 1
              ? board.userData?.unlockTime * 1000 <= new Date().getTime()
                ? t('Cancel the pledge')
                : t('Forced to cancel')
              : t('Cancel the pledge')}
          </IconButtonDiv>
        ) : (
          <IconButton variant="tertiary" onClick={onPresentDeposit} ml="6px">
            <AddIcon color="primary" />
          </IconButton>
        )}
      </IconButtonWrapper>
    )
  }

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

export default StakeAction
