import { Button, Card, Modal, notifier, Typography } from '@tidbcloud/uikit'
import { Form } from '@tidbcloud/uikit/biz'
import { useDisclosure } from '@tidbcloud/uikit/hooks'

import { revokeUserLoginState } from 'dbaas/services/account'
import auth from 'dbaas/services/auth'
import { getErrorMessage } from 'dbaas/services/errorCodes'

import { BlockHeader } from '../components'

export const LogoutAllDevices = () => {
  const onLogoutAllDevices = async () => {
    try {
      await revokeUserLoginState({})
      notifier.info('All sessions have been revoked. Logging you out...', { autoClose: 2200 })
      setTimeout(() => {
        auth.logout()
      }, 2000)
      logoutAllDevicesModalHandlers.close()
    } catch (error) {
      notifier.error(getErrorMessage(error), { autoClose: 2200 })
    }
  }

  const [logoutAllDevicesModalOpened, logoutAllDevicesModalHandlers] = useDisclosure(false)

  return (
    <Card p="xl">
      <BlockHeader
        title="Log Out All Devices"
        description="For your security, you can use this to sign out of all active sessions. This will log you out of all devices, including this one."
        rightSection={
          <Button
            variant="default"
            size="sm"
            color="red"
            data-mp-event="Logout All Devices Button Clicked"
            sx={{ alignSelf: 'center' }}
            onClick={logoutAllDevicesModalHandlers.open}
          >
            Log out all devices
          </Button>
        }
      />
      <Modal
        opened={logoutAllDevicesModalOpened}
        onClose={logoutAllDevicesModalHandlers.close}
        title="Are you sure to log out of all devices?"
      >
        <Form
          onSubmit={onLogoutAllDevices}
          onCancel={logoutAllDevicesModalHandlers.close}
          actionsProps={{
            confirmText: 'Confirm',
            confirmProps: {
              color: 'red',
              variant: 'light',
              'data-mp-event': 'Logout All Devices Confirm Button Clicked'
            }
          }}
        >
          <Typography variant="body-lg">
            This will log you out of all devices, including this one. You will need to log in again.
          </Typography>
        </Form>
      </Modal>
    </Card>
  )
}
