import { useState, useEffect, useContext, useCallback } from 'react'
import { Flex, Card, Alert } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import AuthParticles from './AppParticles'
import FarmControlLogo from '../Logos/FarmControlLogo'
import { AuthContext } from '../Dashboard/context/AuthContext'
import { useLocation, useNavigate } from 'react-router-dom'

const AuthCallback = () => {
  const [isVisible, setIsVisible] = useState(false)
  const [loading, setLoading] = useState(false)
  const [initialized, setInitialized] = useState(false)
  const { getLoginToken } = useContext(AuthContext)
  const location = useLocation()
  const navigate = useNavigate()
  const code = new URLSearchParams(location.search).get('code')
  const state = new URLSearchParams(location.search).get('state')

  const handleGetloginToken = useCallback(async () => {
    await getLoginToken(code)
    setLoading(false)
    navigate(state)
  }, [code, state, navigate, getLoginToken])

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsVisible(true)
    }, 1000)
    if (!initialized && !loading) {
      handleGetloginToken()
      setInitialized(true)
      setLoading(true)
    }
    return () => clearTimeout(timer)
  }, [handleGetloginToken, initialized, loading])

  return (
    <div
      style={{
        backgroundColor: 'black'
      }}
    >
      <div
        style={{
          backgroundColor: 'black',
          minHeight: '100vh',
          transition: 'opacity 0.5s ease-in-out',
          opacity: isVisible ? 1 : 0
        }}
      >
        <AuthParticles />
        <Flex
          align='center'
          justify='center'
          vertical
          style={{ height: '100vh' }}
          gap={'large'}
        >
          <Card style={{ borderRadius: 20 }}>
            <Flex vertical align='center'>
              <FarmControlLogo style={{ fontSize: '500px', height: '40px' }} />
            </Flex>
          </Card>
          <Alert
            message='Loading Farm Control please wait...'
            icon={<LoadingOutlined />}
            showIcon
          />
        </Flex>
      </div>
    </div>
  )
}

export default AuthCallback
