import { Box, Typography } from '@tidbcloud/uikit'
import React, { useEffect, useMemo } from 'react'
import { useLocation } from 'react-router-dom'

import { log } from 'common/log'
import { ErrorPanel } from 'dbaas/components/Error'
import Link from 'dbaas/components/Link'
import { useGAPageView } from 'dbaas/utils/tracking/usePageViewTracking'

import SignIn from './SignIn'
import SignUp from './SignUp'

const FailedCallback = ({ type }: { type: string }) => {
  if (['sent', 'expired', 'system'].indexOf(type) < 0) {
    return <ErrorPanel />
  }

  const errMessage: Record<string, string> = {
    sent: 'Invitation Expired',
    expired: 'Invitation Expired',
    system: 'System Error'
  }

  return (
    <Box bg="white">
      <ErrorPanel message={errMessage[type]} withSupport={false}>
        {type === 'sent' && (
          <Typography variant="body-lg" ta="center">
            A new invitation link has been sent to you. Please check your email.
          </Typography>
        )}
        {type === 'expired' && (
          <Typography variant="body-lg" ta="center">
            Your link has expired or has already been used.
          </Typography>
        )}
        {type === 'system' && (
          <Typography variant="body-lg" ta="center">
            A system error occurred.
          </Typography>
        )}

        <Typography variant="body-lg" ta="center" mt={8}>
          {type === 'sent'
            ? 'If you feel you have reached this message in error, please '
            : type === 'system'
            ? 'Please try again later or '
            : 'Please '}
          contact{' '}
          <Link
            href="mailto:tidbcloud-support@pingcap.com"
            eventName="Tidbcloud Email Support Link Clicked"
            eventParams={{ source: 'Invite' }}
          >
            tidbcloud-support@pingcap.com
          </Link>{' '}
          for assistance.
        </Typography>
      </ErrorPanel>
    </Box>
  )
}

const Login: React.FC<React.PropsWithChildren<unknown>> = () => {
  const { search } = useLocation()
  const urlParams = useMemo(() => new URLSearchParams(search), [search])
  const existed = urlParams.get('existed')
  const status = urlParams.get('status')
  const isError = status !== 'success'
  const errType = urlParams.get('err_type') || ''

  useEffect(() => {
    if (isError) {
      log.warning('InviteCallback error', errType)
    }
  }, [isError, errType])

  useGAPageView()

  if (isError) {
    return <FailedCallback type={errType} />
  }

  return existed === 'true' ? <SignIn /> : <SignUp />
}

export default Login
