import { ArrowBackIcon, ArrowForwardIcon, CheckCircleIcon } from '@chakra-ui/icons'
import {
  Accordion,
  AccordionButton,
  AccordionIcon,
  AccordionItem,
  AccordionPanel,
  Box,
  Button,
  Flex,
  Text,
} from '@chakra-ui/react'
import { useWeb3React } from '@web3-react/core'
import { useRouter } from 'next/router'
import React, { useContext, useEffect, useState } from 'react'
import { Token } from '../../../configs/tokens/types'
import { StepContext } from '../../../contexts'
import CustomModal from '../CustomModal'
import FailedAnimationComponent from '../FailedAnimationComponent'
import SuccessAnimationComponent from '../SuccessAnimationComponent'
import ApprovalToken from './ApprovalToken'

export interface TokenApproval {
  token: Token
  spenderAddress: string
}

interface IModalApprovalProps {
  isOpen: boolean
  onClose: () => void
  approvalTokens: TokenApproval[]
  transactionStatus?: boolean
  isSkipApprovalStep?: boolean
  ContentElement?: any
  getContentElementProps?: any
}

const ModalApproval: React.FunctionComponent<IModalApprovalProps> = (props) => {
  const {
    approvalTokens,
    ContentElement,
    isOpen,
    onClose,
    transactionStatus = false,
    isSkipApprovalStep = false,
    getContentElementProps,
    children,
  } = props
  const { account } = useWeb3React()
  const router = useRouter()
  const { step, setStep, resetStep } = useContext(StepContext)
  const [allowanceList, setAllowanceList] = useState(new Array(approvalTokens.length).fill(0))

  useEffect(() => {
    resetStep()
    return () => {
      resetStep()
    }
  }, [resetStep])

  const setApprovalList = (value, index) => {
    setAllowanceList([...allowanceList.slice(0, index), value, ...allowanceList.slice(index + 1)])
    setStep(step + 1)
  }

  return (
    <CustomModal isOpen={isOpen} onClose={onClose} closeOnOverlayClick={false} header="Listing your item" w={'700px'}>
      <Accordion defaultIndex={[step]} index={[step]} color={'white'}>
        {!isSkipApprovalStep &&
          approvalTokens.map((item, index) => (
            <ApprovalToken
              allowanceKey={index}
              setApprovalList={setApprovalList}
              step={step}
              tokenApproval={item}
              key={index}
              oldAllowance={allowanceList[index]}
            />
          ))}

        <AccordionItem isDisabled={step !== approvalTokens.length}>
          <h2>
            <AccordionButton>
              <Box flex="1" textAlign="left">
                {approvalTokens.length + 1}. Confirm Listing
              </Box>
              <CheckCircleIcon
                fontSize="12px"
                color={step > approvalTokens.length ? 'green.300' : 'gray.300'}
                mr={'10px'}
              />
              <AccordionIcon />
            </AccordionButton>
          </h2>
          <AccordionPanel pb={4}>
            {ContentElement && <ContentElement {...getContentElementProps()} />}
            {children && children}
          </AccordionPanel>
        </AccordionItem>
        <AccordionItem isDisabled={step !== approvalTokens.length + 1}>
          <h2>
            <AccordionButton>
              <Box flex="1" textAlign="left">
                {approvalTokens.length + 2}. Transaction
              </Box>
              <CheckCircleIcon
                fontSize="12px"
                color={step === approvalTokens.length + 1 ? 'green.300' : 'gray.300'}
                mr={'10px'}
              />
              <AccordionIcon />
            </AccordionButton>
          </h2>
          <AccordionPanel>
            <Flex align={'center'} flexDir={'column'} py={'20px'} style={{ gap: '20px' }}>
              {!transactionStatus ? (
                <>
                  <FailedAnimationComponent />
                  <Text color={'red.400'} fontSize={'24px'}>
                    Transaction Failed!
                  </Text>
                </>
              ) : (
                <>
                  <SuccessAnimationComponent />
                  <Text color={'green.400'} fontSize={'24px'}>
                    Transaction Successfully!
                  </Text>
                </>
              )}
              <Flex mt={'20px'} style={{ gap: '20px' }}>
                <Button
                  leftIcon={<ArrowBackIcon />}
                  bg={'transparent'}
                  color={'#00FDFD'}
                  border={'2px solid #00FDFD'}
                  rounded={'10px'}
                  onClick={() => router.push('/')}
                >
                  Go market
                </Button>
                <Button
                  bg={'transparent'}
                  color={'white'}
                  border={'2px solid white'}
                  rounded={'10px'}
                  onClick={onClose}
                >
                  Stay here
                </Button>
                <Button
                  rightIcon={<ArrowForwardIcon />}
                  bg={'transparent'}
                  color={'#00FDFD'}
                  border={'2px solid #00FDFD'}
                  rounded={'10px'}
                  onClick={() => router.push(`/user/${account}`)}
                >
                  Go inventory
                </Button>
              </Flex>
            </Flex>
          </AccordionPanel>
        </AccordionItem>
      </Accordion>
    </CustomModal>
  )
}

export default ModalApproval
