import { Alert, Button, Card, notifier, Typography } from '@tidbcloud/uikit'
import { useInterval } from '@tidbcloud/uikit/hooks'
import { IconInfoCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useEffect, useMemo, useState } from 'react'

import auth, { ConnectionType, databaseConnection } from 'dbaas/services/auth'
import useStores from 'dbaas/stores/useStores'

import { BlockHeader } from '../components'

const authConnectionTypeLabel = {
  [ConnectionType['google-oauth2']]: 'Google',
  [ConnectionType.github]: 'GitHub',
  [ConnectionType.windowslive]: 'Microsoft'
}
const MAX_SECONDS = 60

export const Password = observer(() => {
  const {
    store: {
      userProfile: { email }
    }
  } = useStores()

  const authConnectionType = useMemo(() => auth.getConnectionType() || '', [])
  const updatable = authConnectionType === ConnectionType.auth0
  const [sent, setSent] = useState(false)
  const [seconds, setSeconds] = useState(0)
  const interval = useInterval(() => setSeconds((s) => (s > 0 ? s - 1 : 0)), 1000)
  const updatePasswd = () => {
    setSent(true)
    setSeconds(MAX_SECONDS)
    interval.start()

    auth.auth0.changePassword(
      {
        connection: databaseConnection,
        email
      },
      (err) => {
        if (err) {
          notifier.error(`Failed to update the password: ${err.error}, ${err.errorDescription}`)
        }
      }
    )
  }

  useEffect(() => {
    if (seconds === 0) {
      interval.stop()
    }
  }, [interval, seconds])

  return (
    <Card p="xl">
      <BlockHeader
        title="Password"
        description={
          <Typography variant="body-lg">
            To improve password security, it is recommended to change your password <b>every 90 days</b>.
          </Typography>
        }
        rightSection={
          updatable && (
            <Button
              variant="light"
              disabled={seconds > 0}
              onClick={updatePasswd}
              size="sm"
              data-mp-event="Change Password Button Clicked"
            >
              {seconds > 0 ? `Reset after ${seconds}s` : `Reset`}
            </Button>
          )
        }
        mb="xl"
      />
      {updatable && (
        <Alert icon={<IconInfoCircle />} px={12} py={10}>
          {sent
            ? `An email has just been sent to ${email}, please check your email inbox and follow the instructions to complete the process.`
            : 'To change your password, click the button above. An email will be sent to you with instructions about how to complete the process.'}
        </Alert>
      )}
      {!updatable && (
        <Alert px={12} py={10}>
          You are currently signed in with {authConnectionTypeLabel[authConnectionType] || authConnectionType}, please
          go to the related party to change the password.
        </Alert>
      )}
    </Card>
  )
})
