import { Button } from '@chakra-ui/button'
import { Box, Center, Text } from '@chakra-ui/layout'
import { Image, Skeleton } from '@chakra-ui/react'
import QRCode from 'qrcode.react'
import React, { useCallback, useEffect, useState } from 'react'
import { QRCodeIcon } from '../../../constants'
import { useModal } from '../../../hooks/useModal'
import { useAppDispatch, useAppSelector } from '../../../state/hooks'
import { userActions } from '../../../state/user'
import { selectUserLoading } from '../../../state/user/selectors'
import CustomModal from '../CustomModal'

interface IQRCodeModalProps {
  account?: string
  qrCode?: string
}

const QRCodeModal: React.FunctionComponent<IQRCodeModalProps> = ({ account = '', qrCode = '' }) => {
  const { isOpen, onOpen, onClose } = useModal()
  const dispatch = useAppDispatch()
  const [countdown, setCountdown] = useState(60)
  const [mounted, setMounted] = useState(false)

  const { loadingRefreshQRCode } = useAppSelector(selectUserLoading)

  const timer = useCallback(() => {
    window.setTimeout(() => {
      if (countdown >= 1 && mounted) {
        setCountdown((prev) => prev - 1)
      }
    }, 1000)
  }, [countdown, mounted])

  const handleRefreshQRCode = (isShowToast = true) => {
    window.clearTimeout(timer as any)
    setCountdown(60)
    dispatch(
      userActions.refreshQRCode({
        isShowToast,
      }),
    )
  }

  const handleOnOpen = () => {
    if (countdown <= 0 || mounted === false) {
      handleRefreshQRCode(false)
    }
    onOpen()
    setMounted(true)
  }

  useEffect(() => {
    timer()
    return () => window.clearTimeout(timer as any)
  }, [timer])

  return (
    <>
      <Box
        bg={
          'linear-gradient(116.29deg, rgba(255, 255, 255, 0.35) -29.94%, rgba(255, 255, 255, 0.26) -29.93%, rgba(255, 255, 255, 0.15) 101.76%)'
        }
        transition="all 0.2s"
        border={'1px solid rgba(255,255,255,0.4)'}
        _hover={{
          cursor: 'pointer',
          borderColor: 'primary',
          transform: 'scale(1.1)',
          transition: 'all 0.2s',
        }}
        p={{ base: '12px', md: '20px 30px' }}
        backdropFilter={'blur(46.6183px)'}
        borderRadius={'20px'}
        display={'inline-block'}
        position={'relative'}
        zIndex={'2'}
        onClick={handleOnOpen}
      >
        <Text mb={'14px'} fontSize={'12px'} lineHeight={'18px'} textAlign={'center'} color={'secondary'}>
          My QR Code
        </Text>
        <Center>
          <Image transition="all 0.2s" maxW={{ base: '40px', md: '70px' }} alt={'qr code'} src={QRCodeIcon.src} />
        </Center>
      </Box>
      <CustomModal isOpen={isOpen} onClose={onClose} header="LOGIN WITH YOUR QR CODE">
        <Center>
          <Skeleton isLoaded={loadingRefreshQRCode === false}>
            <Box bg="white" p="20px">
              <QRCode
                value={qrCode}
                size={248}
                bgColor={'#ffffff'}
                fgColor={'#000000'}
                level={'L'}
                includeMargin={false}
                renderAs={'svg'}
                // imageSettings={{
                //   src: '/logo.svg',
                //   x: null,
                //   y: null,
                //   height: 24,
                //   width: 24,
                //   excavate: true,
                // }}
              />
            </Box>
          </Skeleton>
        </Center>
        <Text align="center" fontSize={{ base: '18px', md: '22px' }} mt="32px">
          This QR code will expire in{' '}
          <Text color="#FFBD13" as="span">
            {countdown}
          </Text>{' '}
          seconds
        </Text>
        <Text align="center" fontSize={{ base: '18px', md: '22px' }} mt="18px">
          DO NOT share this QR code to anyone
        </Text>
        <Center>
          <Button
            alignItems="center"
            mt="24px"
            variant="primary"
            onClick={() => handleRefreshQRCode(true)}
            disabled={countdown !== 0 && true}
          >
            Refresh QR CODE
          </Button>
        </Center>
      </CustomModal>
    </>
  )
}

export default React.memo(QRCodeModal)
