import PropTypes from 'prop-types'
import { useContext, useState } from 'react'
import { Result, Typography, Flex, Button } from 'antd'
import { ApiServerContext } from '../../context/ApiServerContext'
import CopyButton from '../../common/CopyButton'
import LockIcon from '../../../Icons/LockIcon'
import ReloadIcon from '../../../Icons/ReloadIcon'

const { Text } = Typography

const SetAppPassword = ({ id }) => {
  const { sendObjectFunction } = useContext(ApiServerContext)
  const [appPassword, setAppPassword] = useState(null)
  const [loading, setLoading] = useState(false)
  const [passwordGenerated, setPasswordGenerated] = useState(false)

  const handleSet = async () => {
    setLoading(true)
    setAppPassword(null)
    try {
      const result = await sendObjectFunction(id, 'user', 'setAppPassword', {})
      if (result?.appPassword) {
        setAppPassword(result.appPassword)
        setPasswordGenerated(true)
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <Flex vertical align='center'>
      <Result
        title={
          passwordGenerated ? 'App Password Generated' : 'Roll New Password'
        }
        disabled={passwordGenerated}
        subTitle={
          appPassword ? (
            <Text>Copy this password now. It will not be shown again.</Text>
          ) : (
            <Text>Generate a new app password for API access.</Text>
          )
        }
        icon={<LockIcon />}
      >
        <Flex justify='center' style={{ minWidth: '395px' }}>
          <Flex justify='center'>
            <Flex gap='small' align='center' justify='center'>
              <Text code style={{ fontSize: '18px' }}>
                {appPassword || '••••••••••••••••••••••••••••••••'}
              </Text>
              <CopyButton size='default' text={appPassword} />
              <Button
                type='texts'
                loading={loading}
                onClick={handleSet}
                icon={<ReloadIcon />}
              />
            </Flex>
          </Flex>
        </Flex>
      </Result>
    </Flex>
  )
}

SetAppPassword.propTypes = {
  id: PropTypes.string.isRequired
}

export default SetAppPassword
