import React from 'react'

type ShareLinkButtonProps = {
  postId: string
  articleUrl: string
}

const ShareLinkButton: React.FC<ShareLinkButtonProps> = ({
  postId,
  articleUrl,
}) => {
  const copyUrl = async (e: React.MouseEvent<HTMLButtonElement>) => {
    const button = e.currentTarget
    const wrapper = e.currentTarget.closest('.x-live-blog-post__link-container')

    wrapper?.setAttribute('data-tooltip', 'show')

    if (typeof window !== 'undefined' && navigator.clipboard) {
      const postUrl = articleUrl ? new URL(articleUrl) : null
      if (postUrl) {
        postUrl.searchParams.append('feature', 'blog-post-sharing')
        postUrl.hash = `post-${postId}`
      }
      await navigator.clipboard.writeText(postUrl?.toString() ?? '')
    }
    setTimeout(() => {
      wrapper?.setAttribute('data-tooltip', 'hide')
      button.blur()
    }, 6000)
  }

  return (
    <div
      className="x-live-blog-post__link-container o3-type-detail"
      data-tooltip="hide"
    >
      <span className="x-live-blog-post__link-copied-message">Link copied</span>
      <button
        className="x-live-blog-post__link-icon o3-button o3-button--ghost o3-button-icon o3-button-icon--icon-only"
        data-component="share-link-button"
        aria-label="Share link"
        data-trackable="share-link"
        title="Link"
        onClick={copyUrl}
      />
      <span>Link</span>
    </div>
  )
}

export default ShareLinkButton
