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 AppPasswordIcon from '../../../Icons/AppPasswordIcon.jsx'
import ReloadIcon from '../../../Icons/ReloadIcon'

const { Text } = Typography

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

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

  return (
    <Flex vertical align='center'>
      <Result
        title={
          passwordGenerated ? 'Secret Regenerated' : 'Regenerate Secret'
        }
        disabled={passwordGenerated}
        subTitle={
          appPassword ? (
            <Text>Copy this secret now. It will not be shown again.</Text>
          ) : (
            <Text>Generate a new secret for this app password.</Text>
          )
        }
        icon={<AppPasswordIcon />}
      >
        <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='text'
                loading={loading}
                onClick={handleRegenerate}
                icon={<ReloadIcon />}
              />
            </Flex>
          </Flex>
        </Flex>
      </Result>
    </Flex>
  )
}

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

export default RegenerateAppPasswordSecret
