import { IconButton } from '@mui/material'
import { ContentCopyOutlined } from '@mui/icons-material'
import type { CopyButtonProps } from './types'
import { copy } from '@carto/ps-utils'

export function CopyButton({
  copyText,
  onSuccess,
  onError,
  'aria-label': ariaLabel,
  ...props
}: CopyButtonProps) {
  async function onCopy() {
    try {
      await copy(copyText)
      onSuccess?.()
    } catch (err) {
      onError?.(err as Error)
    }
  }
  return (
    <IconButton
      size='small'
      onClick={() => void onCopy()}
      aria-label={ariaLabel ?? 'Copy'}
      {...props}
    >
      <ContentCopyOutlined fontSize='small' />
    </IconButton>
  )
}
