import PropTypes from 'prop-types'
import { Button, Tooltip } from 'antd'
import { useMessageContext } from '../context/MessageContext'
import CopyIcon from '../../Icons/CopyIcon'

const CopyButton = ({
  text,
  tooltip = 'Copy',
  size = 'small',
  type = 'text'
}) => {
  const { showSuccess, showError } = useMessageContext()

  const doCopy = (copyText) => {
    if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard
        .writeText(copyText)
        .then(() => {
          showSuccess('Copied to clipboard')
        })
        .catch(() => {
          showError('Failed to copy')
        })
    } else if (
      document.queryCommandSupported &&
      document.queryCommandSupported('copy')
    ) {
      // Legacy fallback
      const textarea = document.createElement('textarea')
      textarea.value = copyText
      textarea.setAttribute('readonly', '')
      textarea.style.position = 'absolute'
      textarea.style.left = '-9999px'
      document.body.appendChild(textarea)
      textarea.select()
      try {
        document.execCommand('copy')
        showSuccess('Copied to clipboard')
      } catch (err) {
        console.error(err)
        console.error(err)
        showError('Failed to copy')
      }
      document.body.removeChild(textarea)
    } else {
      showError('Copy not supported in this browser')
    }
  }

  return (
    <>
      <Tooltip title={tooltip} arrow={false}>
        <Button
          icon={<CopyIcon />}
          style={{ minWidth: 25 }}
          width={20}
          size={size}
          type={type}
          onClick={() => doCopy(text)}
        />
      </Tooltip>
    </>
  )
}

CopyButton.propTypes = {
  text: PropTypes.string.isRequired,
  style: PropTypes.object,
  tooltip: PropTypes.string,
  size: PropTypes.string,
  type: PropTypes.string
}

export default CopyButton
