import { Divider, Box } from '@tidbcloud/uikit'
import { FC } from 'react'

import { SSOButton } from 'dbaas/screens/User/Common/SSO'
import auth, { ConnectionType } from 'dbaas/services/auth'
import { eventTracking } from 'dbaas/utils/tracking'

const getVendorAuthHandler = (vendor: 'GOOGLE' | 'GITHUB' | 'MICROSOFT') => () => {
  return auth.authorizeWithVendor(vendor, window.location.search)
}

const authWithGoogle = getVendorAuthHandler('GOOGLE')
const authWithGithub = getVendorAuthHandler('GITHUB')
const authWithMicrsoft = getVendorAuthHandler('MICROSOFT')

const actionMapping = {
  'sign-in': 'Continue',
  'sign-up': 'Continue'
}

interface SSOLoginProps {
  action: 'sign-in' | 'sign-up'
  beforeAction?: (connectionType: string) => void
}

export const SSOLogin: FC<React.PropsWithChildren<SSOLoginProps>> = ({ action, beforeAction }) => {
  const actionText = actionMapping[action]

  const eventReport = () => {
    eventTracking(`${actionText} With GOOGLE Button Clicked`)
  }

  const onGoogleJoin = async () => {
    await beforeAction?.(ConnectionType['GOOGLE'])
    eventReport()
    authWithGoogle()
  }

  const onGithubJoin = async () => {
    await beforeAction?.(ConnectionType['GITHUB'])
    eventReport()
    authWithGithub()
  }

  const onMicrosoftJoin = async () => {
    await beforeAction?.(ConnectionType['MICROSOFT'])
    eventReport()
    authWithMicrsoft()
  }

  return (
    <Box>
      <SSOButton onClick={onGoogleJoin} connection="google" mb={16}>
        <span>{actionText} with Google</span>
      </SSOButton>
      <SSOButton onClick={onGithubJoin} connection="github" mb={16}>
        <span>{actionText} with GitHub</span>
      </SSOButton>
      <SSOButton onClick={onMicrosoftJoin} connection="microsoft">
        <span>{actionText} with Microsoft</span>
      </SSOButton>
      <Divider label="or" my={8} labelPosition="center"></Divider>
    </Box>
  )
}
