import { Alert, Box, Button, Flex, Typography } from '@tidbcloud/uikit'
import { IconCheckCircle, IconXCircle } from '@tidbcloud/uikit/icons'
import React, { useEffect, useRef, useState } from 'react'

import { FormErrorMessage } from 'dbaas/components/Form'
import Link from 'dbaas/components/Link'
import { sendVerificationEmail } from 'dbaas/services/account'
import auth from 'dbaas/services/auth'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import { consumeEmailLakeConnectIntent, getLakeConnectTrackingProperties } from 'dbaas/utils/lake-connect'
import { eventTracking, MixpanelEvents } from 'dbaas/utils/tracking'
import { useCountingDown } from 'dbaas/utils/useCountingDown'

import { SigninField } from './Common/FormFields'
import { PageShell } from './Common/Shell'
import { getEmail } from './utils'

const CompleteSignUp = ({ email }: { email: string }) => {
  const { counter } = useCountingDown(true, 5, false)
  const loginStarted = useRef(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 login = () => {
    if (loginStarted.current) {
      return
    }
    loginStarted.current = true

    const lakeConnectIntent = consumeEmailLakeConnectIntent((loginSearch, intent) => {
      eventTracking(MixpanelEvents.TidbCloudLake.Validate.RequestStarted, {
        entry: 'email_verification',
        ...getLakeConnectTrackingProperties(intent)
      })

      if (auth.isAuthenticated()) {
        auth.logout(`/signin${loginSearch}`, false)
      } else {
        auth.login(loginSearch)
      }
    })

    if (lakeConnectIntent) {
      return
    }

    // multi org login
    if (!auth.isAuthenticated()) {
      return auth.login(window.location.search)
    }
    return auth.logout()
  }

  useEffect(() => {
    if (counter === 0) {
      // redirect to the sign in page
      login()
    }
  }, [counter])

  const handleClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    e.preventDefault()
    login()
  }

  return (
    <Flex direction="column">
      <Typography variant="headline-lg" color="gray.8">
        Sign Up
      </Typography>
      <Alert color="green" icon={<IconCheckCircle size={14} />} mt="md">
        Your account ({email}) has been successfully activated!
      </Alert>
      <Typography variant="body-lg" mt="sm">
        You will be redirected to the sign in page after <strong>{counter} s</strong> or click Sign In .
      </Typography>
      <Button onClick={handleClick} mt="sm">
        Sign In
      </Button>
      <Typography variant="body-lg" mt="sm">
        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.
        <br />
      </Typography>
    </Flex>
  )
}

export default () => {
  const params = new URLSearchParams(window.location.search)
  const status = params.get('status')
  const errType = params.get('err_type')
  const fromPage = params.get('from')
  const email = getEmail(params.get('email') || '')
  // 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)

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

  useEffect(() => {
    if (status === 'failed') {
      // tracking "Create Account Failed"
      eventTracking('Create Account Failed', {
        'Error Type': errType,
        'Error Message': errType ? 'Verification Expired' : 'System Error Occurred'
      })
    }
  }, [status, errType])

  const ResendBox = ({ content = 'Resend' }: { content?: string }) => (
    <Box w="100%" my={16}>
      <Button
        w="100%"
        disabled={sending}
        data-mp-event="Resend Verification Email Button Clicked"
        onClick={handleResend}
      >
        {sending ? `Resend verification email(${counter}s)` : content}
      </Button>
      {error && (
        <Box mt="md">
          <FormErrorMessage message={error} />
        </Box>
      )}
    </Box>
  )

  async function handleResend() {
    try {
      await sendVerificationEmail({ email })

      setSending(true)
    } catch (e) {
      const message = getErrorMessage(e)

      eventTracking('Resend Verification Email Failed', {
        'Error Message': message
      })
      setError(message)
    }
  }

  return (
    <PageShell>
      <Flex mt={36} w={360}>
        {status === 'verifying' ? (
          <Flex direction="column">
            <Flex align="baseline" justify="space-between">
              <Typography variant="headline-lg" color="gray.8">
                Sign Up
              </Typography>
              <SigninField />
            </Flex>
            <Alert color="green" icon={<IconCheckCircle size={14} />} mt="md">
              We have sent you a verification email to activate your account.
            </Alert>
            <ResendBox />
            <Typography variant="body-lg">
              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>
          </Flex>
        ) : status === 'success' ? (
          <CompleteSignUp email={email} />
        ) : (
          <Flex direction="column" w="100%">
            <Typography variant="headline-lg" color="gray.8">
              Sign Up
            </Typography>

            <>
              {errType === 'expired' ? (
                <Alert color="red" icon={<IconXCircle />} mt="xs">
                  Your verification link has expired.
                </Alert>
              ) : errType === 'sent' ? (
                <Alert color="green" icon={<IconCheckCircle size={14} />} mt="xs">
                  We have sent you({email}) a verification email.
                </Alert>
              ) : (
                <Alert color="red" icon={<IconXCircle />} mt="xs">
                  Your verification link has expired. Some unknown issue occurred. Please try resending the verification
                  email or contact{' '}
                  <Link href="mailto:tidbcloud-support@pingcap.com" eventName="Tidbcloud Email Support Link Clicked">
                    tidbcloud-support@pingcap.com
                  </Link>{' '}
                  for assistance.
                </Alert>
              )}
              <ResendBox content="Resend verification email" />
            </>
          </Flex>
        )}
      </Flex>
    </PageShell>
  )
}
