import React, { useState, useRef } from 'react'
import { string, node } from 'prop-types'
import { Input, Form } from 'antd'
import './CopyLinkInput.less'

function CopyLinkInput({ joinLink, label, className = '', icon }) {
  const [copied, copyLink] = useState(false)
  const timeoutId = useRef(null)

  const renderIcon = () => {
    if (!icon) return <i className="fa fa-clipboard" />

    return icon
  }

  async function copyToClipboard(text) {
    try {
      await navigator.clipboard.writeText(text)
    } catch (err) {
      console.error('Could not copy text: ', err)
    }
  }

  const clearCopyTimeout = () => {
    if (timeoutId?.current) {
      clearTimeout(timeoutId.current)
    }
  }
  const onCopyLink = async () => {
    copyToClipboard(joinLink)
    copyLink(true)

    timeoutId.current = setTimeout(() => {
      clearCopyTimeout()
      copyLink(false)
    }, 2000)
  }

  return (
    <Form.Item
      className={className}
      label={label}
      help={
        copied && <div className="embed-code-copied">Link copied to clipboard {renderIcon()}</div>
      }>
      <Input
        className="copy-link-input"
        size="large"
        value={joinLink}
        readOnly
        addonAfter={
          <button type="button" className="copy-link" onClick={onCopyLink} target="_blank">
            {renderIcon()}
          </button>
        }
        onClick={onCopyLink}
      />
    </Form.Item>
  )
}

CopyLinkInput.propTypes = {
  joinLink: string.isRequired,
  label: string,
  className: string,
  icon: node,
}

CopyLinkInput.defaultProps = {
  label: '',
  className: '',
  icon: null,
}

export default CopyLinkInput
