import { CheckCircleIcon, LockIcon } from '@chakra-ui/icons'
import { AccordionButton, AccordionIcon, AccordionItem, AccordionPanel, Box, Button, Text } from '@chakra-ui/react'
import React, { useEffect } from 'react'
import Lottie from 'react-lottie'
import { TokenApproval } from '.'
import { TermsAnimation } from '../../../constants'
import useTokenAllowance from '../../../hooks/useTokenAllowance'
import Loading from '../Loading'

interface IApprovalTokenProps {
  allowanceKey: number
  tokenApproval: TokenApproval
  setApprovalList: (value: number, index: number) => void
  step: number
  oldAllowance: number
}

const ApprovalToken: React.FunctionComponent<IApprovalTokenProps> = (props) => {
  const { setApprovalList, tokenApproval, allowanceKey, step, oldAllowance } = props
  const defaultOptions = {
    loop: true,
    autoplay: true,
    animationData: TermsAnimation,
    rendererSettings: {
      preserveAspectRatio: 'xMidYMid slice',
    },
  }

  const { allowance, increaseAllowance, loadingGetAllowance, loadingIncreaseAllowance } = useTokenAllowance(
    tokenApproval.token,
    tokenApproval.spenderAddress,
  )
  useEffect(() => {
    if (oldAllowance !== allowance) {
      setApprovalList(allowance, step)
    }
  }, [allowance, oldAllowance, setApprovalList, step])

  return (
    <AccordionItem isDisabled={allowance > 0 || step < allowanceKey}>
      <h2>
        <AccordionButton>
          <Box flex="1" textAlign="left">
            {allowanceKey + 1}. Approve {tokenApproval.token.tokenSymbol}
          </Box>
          <CheckCircleIcon
            fontSize="12px"
            color={allowance > 0 || step > allowanceKey ? 'green.300' : 'gray.300'}
            mr={'10px'}
          />
          <AccordionIcon />
        </AccordionButton>
      </h2>
      <AccordionPanel pb={4} display={'flex'} flexDir={'column'} alignItems={'center'} style={{ gap: '10px' }}>
        {loadingGetAllowance && <Loading />}

        {!loadingGetAllowance && (
          <>
            <Box mx="auto" maxW="350px">
              <Lottie
                options={defaultOptions}
                isClickToPauseDisabled={true}
                isStopped={false}
                isPaused={false}
                speed={0.8}
              />
            </Box>
            <Text>
              We’ll ask your approval for the marketplace to access your token. This is a one-time only operation.
            </Text>
            <Button
              w={'full'}
              bg={'white'}
              fontFamily={'secondary'}
              leftIcon={<LockIcon />}
              onClick={() => increaseAllowance()}
              isLoading={loadingIncreaseAllowance}
            >
              Approve
            </Button>{' '}
          </>
        )}
      </AccordionPanel>
    </AccordionItem>
  )
}

export default ApprovalToken
