import { Box, Card, Button, Flex, Typography } from '@tidbcloud/uikit'
import { IconArrowRight } from '@tidbcloud/uikit/icons'
import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'

import { Logo } from 'dbaas/components'
import auth, { ConnectionType, SSOTypes } from 'dbaas/services/auth'
import { eventTracking, getUTMSource } from 'dbaas/utils/tracking'
import { useGAPageView } from 'dbaas/utils/tracking/usePageViewTracking'
import { forwardSearch } from 'dbaas/utils/useQuery'
import Ossinsight from 'media/logo-ossinsight.svg?react'
import darkBg from 'media/signup-bg-v2-dark.svg'

import { SSOButton, SSOConnection } from '../Common/SSO'

export default () => {
  const history = useHistory()

  const params = new URLSearchParams(window.location.search)
  const email = params.get('email')
  const connection = (params.get('connection') as SSOConnection) || ''
  const forwardParams = forwardSearch(window.location.search, {
    prev_referrer: document.referrer,
    website_referrer_url: params.get('website_referrer_url') || document.referrer
  })
  const utm = getUTMSource()
  const eventParams = {
    channel: utm.utm_source || utm.utm_campaign,
    utm
  }

  const goToFreeTrial = () => {
    history.replace(`/free-trial${window.location.search}`)
  }

  const onSignup = () => {
    const vendor = connection?.toUpperCase() || ''
    auth.authorizeWithVendor(vendor, forwardParams)
  }

  const allowedContinue =
    [ConnectionType.github, ConnectionType['google-oauth2'], ConnectionType.windowslive].includes(
      connection.toUpperCase() as Exclude<SSOTypes, 'OIDC' | 'SAML'>
    ) && email

  const authInfo = auth.getAuthInfo()

  const isRegistered = auth.isAuthenticated() && authInfo.email === email

  useEffect(() => {
    eventTracking('Channel Page View', {
      registered: isRegistered,
      email,
      connection
    })
    if (isRegistered) {
      history.push('/')
      return
    }
    if (!email && !connection) {
      eventTracking('Unauthorized User to Free Trial')
      goToFreeTrial()
    }
  }, [isRegistered, email, connection])

  useGAPageView()

  // already sigin in
  if (isRegistered || (!email && !connection)) {
    return null
  }

  return (
    <Flex
      direction="column"
      sx={() => ({
        backgroundColor: '#000000',
        height: '100vh',
        width: '100%',
        position: 'relative',
        backgroundImage: `url(${darkBg})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center center'
      })}
    >
      <Box sx={{ position: 'absolute', left: 32, top: 32 }}>
        <Logo withText={true} colorScheme="dark" width={300} height={50} />
      </Box>
      <Flex
        justify="center"
        align="center"
        sx={{
          maxWidth: '85rem',
          width: '100%',
          flex: 1,
          margin: '0 auto'
        }}
      >
        <Card w={440} p={40} sx={{ 'button, p': { marginTop: 24 } }}>
          <Flex color="carbon.8" justify="center" align="center" mb={24}>
            <Ossinsight />
            <IconArrowRight size={24} mx={32} />
            <Logo withText={false} width={40} height={40} viewBox="0 0 50 50" />
          </Flex>
          <Typography variant="headline-md" c="carbon.8" ta="center">
            Explore Data on TiDB Cloud with
          </Typography>
          <SSOButton
            connection={allowedContinue && connection ? connection : undefined}
            onClick={() => {
              eventTracking('Channel SSO Button Clicked', eventParams)
              onSignup()
            }}
            disabled={!allowedContinue}
            labelProps={{ w: 'auto' }}
          >
            <Typography variant="action-md" lh="24px" c="carbon.8" mt={0}>
              {email}
            </Typography>
          </SSOButton>
          <Button
            w="100%"
            h={40}
            disabled={!allowedContinue}
            onClick={() => {
              eventTracking('Channel Continue Button Clicked')
              onSignup()
            }}
            data-mp-event="mp-continue-1691461013772"
          >
            Continue
          </Button>
          <Flex fw={500} fz={14} mt={24} gap={8}>
            <Typography variant="body-lg" fw={500} lh="24px" color="carbon.7" mt={0}>
              Want to switch another email?
            </Typography>
            <a
              onClick={() => {
                eventTracking('Channel Click here Button Clicked', eventParams)
                goToFreeTrial()
              }}
            >
              Click here
            </a>
          </Flex>
        </Card>
      </Flex>
    </Flex>
  )
}
