import * as Sentry from '@sentry/react'
import { Box, Card, Divider, Typography } from '@tidbcloud/uikit'
import { Form, FormCheckbox } from '@tidbcloud/uikit/biz'
import { observer } from 'mobx-react'
import { useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'

import PageLoader from 'dbaas/components/Placeholder'
import { CloudProviderConst } from 'dbaas/features/Project'
import { configFeatureFlagForProviderSource } from 'dbaas/services/account'
import { updateAuth0AuditLog } from 'dbaas/services/api'
import { CentralAuth0AuditLogReqOperation } from 'dbaas/services/api/interface'
import { ExpFeatHashmap } from 'dbaas/stores/localStorage'
import { ram } from 'dbaas/stores/ram'
import useStores from 'dbaas/stores/useStores'
import { eventTracking, identifyUser } from 'dbaas/utils/tracking'
import TiDBCloudLogo from 'media/logo/tidb-cloud-logo-v2.svg'

import { BackgroundMask } from '../Common/Background'

export const Program = observer(() => {
  const {
    store: {
      tenantData: { name: orgName, id },
      expWhiteList
    },
    actions
  } = useStores()
  const history = useHistory()
  const isEnrolled = expWhiteList[ExpFeatHashmap.EnableAlibabaCloudOrgs]
  const [loaded, setLoaded] = useState(false)

  const onSubmit = async () => {
    if (isEnrolled) {
      return history.push('/')
    }
    await configFeatureFlagForProviderSource(id, {
      provider_source: CloudProviderConst.ALICLOUD
    })
    actions.fetchWhiteList()
    history.push('/')
  }

  useEffect(() => {
    async function fetch() {
      const lastVisit = await actions.fetchLastVisit()
      actions.fetchFeatureList(lastVisit?.org_id)
      Promise.all([
        actions.fetchUserProfileV2().then((data) => {
          const [user, tenant] = data
          Sentry.setUser({
            id: user.user_id,
            email: user.email
          })

          // logging to mixpanel
          identifyUser(
            { ...user, id: user.user_id },
            { third_party_account_provider: tenant.third_party_account_provider || '' }
          )
          // retrieve billing info
          actions.fetchTenantPlanInfo()
        }),
        actions.fetchWhiteList()
      ]).finally(() => {
        setLoaded(true)
      })

      if (ram.get('reportLogin')) {
        eventTracking('Login')
        updateAuth0AuditLog(
          {
            operation: CentralAuth0AuditLogReqOperation.SIGNIN,
            is_success: true,
            failure_info: '',
            org_id: lastVisit.org_id || ''
          },
          { isHandleErr: true }
        )
        ram.clear('reportLogin')
      }
    }
    fetch()
  }, [actions])

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

  return (
    <Box
      bg="carbon.1"
      sx={(theme) => ({
        display: 'flex',
        flexDirection: 'column',
        height: '100vh',
        alignItems: 'center',
        justifyContent: 'center',
        position: 'relative',
        backgroundColor: theme.white
      })}
    >
      <BackgroundMask></BackgroundMask>
      <Box
        sx={{
          position: 'absolute',
          top: 24,
          left: 24,
          width: 135,
          height: 30,
          background: `url(${TiDBCloudLogo}) center/contain no-repeat`
        }}
      ></Box>
      <Card shadow="none" w={650} p={0}>
        <Box p={24} pb={0}>
          <Typography variant="headline-md" c="carbon.9">
            Accept TiDB Cloud Preview Terms
          </Typography>
          <Typography variant="body-lg" c="carbon.8" mt={24}>
            {isEnrolled ? (
              <>
                Your organization(<b>{orgName}</b>) has already joined the Alibaba Cloud Program. Click 'Get Started' to
                explore.
              </>
            ) : (
              <>
                To have your organization (<b>{orgName}</b>) join the Alibaba Cloud Program, please review and accept
                the following terms.
              </>
            )}
          </Typography>
        </Box>
        <Form<{ accept_terms: boolean }>
          onSubmit={onSubmit}
          defaultValues={{
            accept_terms: false
          }}
          errorMessageProps={{
            mx: 24
          }}
          actionsProps={{
            px: 24,
            pb: 24,
            cancelProps: {
              onClick: () => {
                history.replace('/')
              },
              display: isEnrolled ? 'none' : undefined
            },
            confirmProps: {
              onClick: () => {
                eventTracking('Confirm to Join Alibaba Cloud Program')
              }
            },
            confirmText: 'Get Started'
          }}
        >
          {!isEnrolled && (
            <FormCheckbox
              p={24}
              mb={-16}
              name="accept_terms"
              rules={{
                validate: (value) => {
                  if (!value) {
                    return 'Please accept to get started.'
                  }
                  return true
                }
              }}
              label={
                <>
                  I agree to the{' '}
                  <a
                    href="https://www.pingcap.com/legal/tidb-cloud-public-preview-terms-and-conditions/"
                    target="_blank"
                    rel="noreferrer"
                  >
                    TiDB Cloud Public Preview Terms and Conditions
                  </a>
                  .
                </>
              }
            />
          )}
          <Divider mt={isEnrolled ? 24 : undefined}></Divider>
        </Form>
      </Card>
    </Box>
  )
})

export default Program
