import _get from 'lodash/get'
import _identity from 'lodash/identity'
import React, { useRef } from 'react'

interface ICopyFieldProps {
  copyValue: string;
  onLinkCopied?: () => void;
  copyIconSrc?: string;
  copyTitle?: string;
  hasCopyIcon: boolean;
  classNamePrefix?: string;
  messageText?: string;
}

export const CopyField = (props: ICopyFieldProps) => {
  const {
    copyValue,
    copyIconSrc = 'https://img.icons8.com/office/50/000000/copy.png',
    copyTitle = 'Copy',
    hasCopyIcon = false,
    onLinkCopied = _identity,
    classNamePrefix = '',
    messageText = '',
  } = props

  const inputRef = useRef(null)

  return (
    <>
      {messageText && <span className="message-text">{messageText}</span>}
      <input
        ref={inputRef}
        className={`${classNamePrefix}_share-input`}
        defaultValue={copyValue}
        readOnly={true}
      />
      <div
        className={`${classNamePrefix}_share-by-link-copy-icon`}
        aria-hidden={true}
        onClick={() => {
          navigator.clipboard.writeText(_get(inputRef, 'current.value'))
          onLinkCopied()
        }}
      >
        {hasCopyIcon ? (
          <img src={copyIconSrc} alt="copy" />
        ) : (
          <span className={`${classNamePrefix}_copy-icon`}>{copyTitle}</span>
        )}
      </div>
    </>
  )
}
