import { Button, Card, Center, Typography, Flex, CardProps, Divider } from '@tidbcloud/uikit'
import { FormErrorMessage } from '@tidbcloud/uikit/biz'
import { IconAlertCircle, IconCheckCircle, IconMail05 } from '@tidbcloud/uikit/icons'
import { useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'

import Link from 'dbaas/components/Link'
import { getEmail } from 'dbaas/screens/User/utils'
import { sendVerificationEmail } from 'dbaas/services/account'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import { getSafeReturnTo } from 'dbaas/utils/returnTo'
import { eventTracking } from 'dbaas/utils/tracking'
import { useCountingDown } from 'dbaas/utils/useCountingDown'

import { OAUTH_AUTHORIZE } from '../Components/constants'
import { useIsMdScreen } from '../Components/helpers'
import { PageShell } from '../Components/Shell'

const CompleteSignUp = ({ email, returnTo }: { email: string; returnTo: string | null }) => {
  const { counter } = useCountingDown(true, 5, false)

  useEffect(() => {
    // identify 'Create Account' event, which means the user files out the sign-up form, verify the email, and created a new account successfully.
    eventTracking('Create Account')
  }, [])

  const onContinue = () => {
    window.location.href = returnTo || '/oauth/signin'
  }

  useEffect(() => {
    if (counter === 0) {
      // redirect to the sign in page
      window.location.href = returnTo || '/oauth/signin'
    }
  }, [counter, returnTo])

  const handleClick = () => {
    onContinue()
  }

  return (
    <Card w={606} p={40}>
      <Center>
        <IconCheckCircle c="green" size={40} />
      </Center>
      <Typography variant="headline-lg" ta="center" mt={16}>
        {email}
      </Typography>
      <Typography variant="headline-md" mt={16} ta="center">
        Your account has been successfully activated!
      </Typography>
      <Center mt={24}>
        <Button onClick={handleClick}>Continue({counter}s)</Button>
      </Center>
      <Divider my={24} />
      <Typography variant="label-lg" ta="center">
        Click to open <a href="/">TiDB Cloud</a> web console
      </Typography>
      <Typography variant="label-lg" ta="center" mt={24}>
        Please contact{' '}
        <Link href="mailto:tidbcloud-support@pingcap.com" eventName="Tidbcloud Email Support Link Clicked">
          tidbcloud-support@pingcap.com
        </Link>{' '}
        if you have any questions.
      </Typography>
    </Card>
  )
}

export default () => {
  const params = new URLSearchParams(window.location.search)
  const usage = params.get('usage')
  const fromPage = params.get('from')
  const status = params.get('status')
  const errType = params.get('err_type')
  const email = getEmail(params.get('email') || '')
  const returnTo = getSafeReturnTo(params.get('returnTo'))
  const history = useHistory()
  // start counting down immediately after finishing sign up
  const [sending, setSending] = useState(fromPage === 'signup')
  const [error, setError] = useState<string | null>(null)
  const { counter } = useCountingDown(sending)

  const isMd = useIsMdScreen()

  const cardProps: Omit<CardProps, 'children'> = isMd
    ? {
        w: 472,
        p: 40,
        shadow: 'none'
      }
    : {
        w: 606,
        p: 40
      }

  const isAuthorize = usage === OAUTH_AUTHORIZE

  const ResendBox = ({ content = 'Resend' }: { content?: string }) => (
    <Flex justify="center" mt={16} direction="column">
      <Flex justify="center" gap={24}>
        <Button
          disabled={sending}
          miw={164}
          data-mp-event="Resend Verification Email Button Clicked"
          onClick={handleResend}
        >
          {sending ? `Resend Email (${counter}s)` : content}
        </Button>
        {isAuthorize && (
          <Button
            variant="default"
            onClick={() => history.push(`/oauth/signin${returnTo ? '?returnTo=' + encodeURIComponent(returnTo) : ''}`)}
          >
            Back and Reconnect
          </Button>
        )}
      </Flex>
      {error && <FormErrorMessage mt={8} message={error} />}
    </Flex>
  )

  async function handleResend() {
    try {
      await sendVerificationEmail({
        email,
        return_url: returnTo ? encodeURIComponent(`/oauth/signin?returnTo=${encodeURIComponent(returnTo)}`) : undefined
      })
      setSending(true)
    } catch (e) {
      const message = getErrorMessage(e)
      eventTracking('Resend Verification Email Failed', {
        'Error Message': message
      })
      setError(message)
    }
  }

  useEffect(() => {
    if (counter === 0) {
      setSending(false)
    }
  }, [counter])

  return (
    <PageShell>
      <Flex>
        {status === 'success' ? (
          <CompleteSignUp email={email} returnTo={returnTo} />
        ) : status === 'verifying' ? (
          <Card {...cardProps}>
            <Center>
              <IconMail05 size={40} c="carbon.7" />
            </Center>
            <Typography variant="headline-lg" ta="center" mt={16}>
              Please verify your email address
            </Typography>
            <Typography variant="action-lg" c="carbon.8" ta="center" mt={16} m="0 auto">
              A verification email has been sent to
              <br />
              <a href={`mailto:${email}`}>{email}</a>
              <br />
              Click the link in the email to verify your email address.
            </Typography>
            <ResendBox />
            <Divider my={24} />
            <Typography variant="body-lg" ta="center">
              Can't receive email? Please contact{' '}
              <Link href="mailto:tidbcloud-support@pingcap.com" eventName="Tidbcloud Email Support Link Clicked">
                tidbcloud-support@pingcap.com
              </Link>{' '}
              for assistance.
            </Typography>
          </Card>
        ) : (
          <Card w={606} p={40}>
            <Flex direction="column" align="center">
              <IconAlertCircle size={40} c="red" />

              <Typography variant="headline-md" mt={16}>
                {errType ? 'Verification Expired' : 'System Error Occurred'}
              </Typography>

              {errType === 'sent' && (
                <>
                  <Typography variant="body-lg" mt={16}>
                    A new verification has been sent to you. Please check your email.
                  </Typography>
                  <Typography variant="body-lg" ta="center" mt={8}>
                    If you feel you have reached this message in error, please contact{' '}
                    <Link href="mailto:tidbcloud-support@pingcap.com" eventName="Tidbcloud Email Support Link Clicked">
                      tidbcloud-support@pingcap.com
                    </Link>{' '}
                    for assistance.
                  </Typography>
                </>
              )}

              {errType === 'expired' && (
                <>
                  <Typography variant="body-lg" mt={16}>
                    Your verification link has expired.
                  </Typography>
                  <Typography variant="body-lg" mt={16}>
                    Please click the button below to resend.
                  </Typography>
                  <ResendBox content="Resend Verification" />
                </>
              )}
            </Flex>
          </Card>
        )}
      </Flex>
    </PageShell>
  )
}
