import * as Sentry from '@sentry/react'
import { useMount } from 'ahooks'
import { observer } from 'mobx-react'
import { useState } from 'react'
import { Redirect } from 'react-router-dom'

import { PageLoader } from 'dbaas/components/Placeholder'
import { updateAuth0AuditLog } from 'dbaas/services/api'
import { CentralAuth0AuditLogReqOperation } from 'dbaas/services/api/interface'
import { ram } from 'dbaas/stores/ram'
import useStores from 'dbaas/stores/useStores'
import { eventTracking, identifyUser } from 'dbaas/utils/tracking'

import { markDedicatedOnboardingDone } from './helpers'

const startingPage = '/clusters/create-cluster?tier=dedicated'

export const DedicatedOnboarding = observer(() => {
  const {
    actions: { fetchUserProfileV2, fetchTenantPlanInfo }
  } = useStores()
  const [inited, setInited] = useState(false)

  useMount(async () => {
    const [user, org] = await fetchUserProfileV2()

    // Once the initialization finished, mark the flag as done
    setInited(true)
    markDedicatedOnboardingDone()

    /**
     * The following steps are the same as those in `App.tsx`
     */
    Sentry.setUser({
      id: user.user_id,
      email: user.email
    })
    identifyUser(
      {
        ...user,
        id: user.user_id
      },
      {
        third_party_account_provider: org.third_party_account_provider || ''
      }
    )
    if (ram.get('reportLogin')) {
      eventTracking('Login')
      updateAuth0AuditLog(
        {
          operation: CentralAuth0AuditLogReqOperation.SIGNIN,
          is_success: true,
          failure_info: '',
          org_id: org.id || ''
        },
        { isHandleErr: true }
      )
      ram.clear('reportLogin')
    }
    fetchTenantPlanInfo()
  })

  if (!inited) {
    return <PageLoader />
  }

  return <Redirect to={startingPage} />
})
