import { Alert, Box, Button, Divider, Flex, Group, Modal, notifier, Typography } from '@tidbcloud/uikit'
import { Form, FormActions, FormErrorMessage, FormPasswordInput, FormTextInput } from '@tidbcloud/uikit/biz'
import { IconAlertTriangle } from '@tidbcloud/uikit/icons'
import DOMPurify from 'dompurify'
import { useEffect, useState } from 'react'

import { disableMFA, useDisableMFA } from 'dbaas/services/account'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import { eventTracking } from 'dbaas/utils/tracking'

interface TwoFADisablingProps {
  opened: boolean
  onClose: () => void
  onConfirm: () => void
  updating?: boolean
}

export const TwoFADisablingForSSO = ({ opened, onClose, onConfirm, updating }: TwoFADisablingProps) => {
  const updator = useDisableMFA({
    mutation: {
      onSuccess: () => {
        onConfirm()
      },
      onError: (error) => {
        const message = getErrorMessage(error, true)

        notifier.error(<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(message) }} />)
      }
    }
  })
  const disable = () => {
    return updator.mutateAsync({
      data: {
        password: '',
        otp_code: ''
      }
    })
  }

  return (
    <Modal title="Disable Multi-Factor Authentication" centered size="lg" opened={opened} onClose={onClose}>
      <Typography variant="body-lg" mb="xl">
        You are logging in to TiDB Cloud through SSO authentication. Please visit provider to set up MFA for your
        account.
      </Typography>
      <Group justify="flex-end">
        <Button
          variant="default"
          onClick={onClose}
          data-mp-event="Cancel disabling multi-factor authentication button clicked"
        >
          Cancel
        </Button>
        <Button
          variant="light"
          color="red"
          loading={updator.isLoading || updating}
          onClick={disable}
          data-mp-event="Confirm disabling multi-factor authentication button clicked"
        >
          Disable
        </Button>
      </Group>
    </Modal>
  )
}

export const TwoFADisabling = ({ opened, onClose, onConfirm, updating: _updating }: TwoFADisablingProps) => {
  const [type, setType] = useState<'digit' | 'recovery'>('digit')

  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const onSubmit = async (data: { password: string; otp_code: string; recovery_code: string }) => {
    setLoading(true)
    setError('')
    try {
      await disableMFA(
        type === 'digit'
          ? {
              password: data.password,
              otp_code: data.otp_code
            }
          : {
              password: data.password,
              recovery_code: data.recovery_code
            }
      )
      notifier.success('Disabled MFA successfully!')
      onConfirm()
    } catch (e) {
      setError(getErrorMessage(e))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (!opened) {
      setTimeout(() => {
        setType('digit')
        setError('')
      }, 100)
    }
  }, [opened])

  const AccountField = () => {
    return (
      <Box>
        <FormPasswordInput label="Account Password" name="password" />
        <Box
          component="a"
          href={window.location.origin + '/forgot_password'}
          target="_blank"
          mt={8}
          display="inline-block"
        >
          Forgot password?
        </Box>
      </Box>
    )
  }

  return (
    <Modal
      title="Disable Multi-Factor Authentication"
      centered
      size="lg"
      opened={opened}
      onClose={onClose}
      returnFocus={false}
    >
      <Form
        onSubmit={onSubmit}
        actionsProps={{
          cancelProps: {
            'data-mp-event': 'Cancel disabling multi-factor authentication button clicked'
          },
          confirmProps: {
            variant: 'light',
            color: 'red',
            'data-mp-event': 'Confirm disabling multi-factor authentication button clicked'
          },
          mt: 16,
          mb: -8
        }}
        withActions={false}
      >
        <Alert color="yellow" icon={<IconAlertTriangle />} styles={{ root: { padding: '10px 12px' } }}>
          By removing this, you will no longer have Multi-Factor Authentication sign in on your account.
        </Alert>
        {type === 'digit' ? (
          <>
            <Typography variant="body-lg">
              Enter your account password and get a verification code from the Google Authenticator (or similar) app to
              confirm this is the action you'd like to take.
            </Typography>
            <AccountField />
            <FormTextInput
              label="MFA Verification Code"
              key="otp_code"
              name="otp_code"
              placeholder="Enter the 6-digit code"
              rules={{ required: 'Required' }}
            />
            <Typography variant="body-lg" c="carbon.7">
              Lost your mobile device?{' '}
              <Typography
                c="peacock.7"
                sx={{ cursor: 'pointer' }}
                display="inline-block"
                onClick={() => {
                  setType('recovery')
                  setError('')
                  eventTracking('Use the recovery code Button Clicked')
                }}
              >
                Use the recovery code
              </Typography>
            </Typography>
          </>
        ) : (
          <>
            <Typography variant="body-lg">
              Enter recovery code to confirm this is the action you'd like to take.
            </Typography>
            <AccountField />
            <FormTextInput
              label="Recovery Code"
              name="recovery_code"
              key="recovery_code"
              placeholder="Enter your recovery code"
              rules={{ required: 'Required' }}
            />
          </>
        )}
        {!!error && <FormErrorMessage message={error} onDismiss={() => setError('')} />}
        <Divider mx={-24} mt={8} />
        <Flex justify={type === 'recovery' ? 'space-between' : 'flex-end'} align="center" mb={-8}>
          {type === 'recovery' && (
            <Button
              variant="default"
              onClick={() => {
                setType('digit')
                setError('')
              }}
            >
              Back
            </Button>
          )}
          <FormActions
            loading={loading}
            mt={0}
            onCancel={onClose}
            cancelProps={{
              'data-mp-event': 'Cancel to disable MFA Button Clicked'
            }}
            confirmProps={{ 'data-mp-event': 'Confirm to disable MFA Button Clicked', 'data-mp-event-type': type }}
          />
        </Flex>
      </Form>
    </Modal>
  )
}
