import React, { useEffect, useState } from 'react'

function fallbackCopyText(text) {
  const textarea = document.createElement('textarea')
  textarea.value = text
  textarea.setAttribute('readonly', 'true')
  textarea.style.position = 'fixed'
  textarea.style.opacity = '0'
  document.body.appendChild(textarea)
  textarea.select()
  document.execCommand('copy')
  document.body.removeChild(textarea)
}

export default function ShareLinkButton({
  href = '',
  label = 'Copiar link',
  copiedLabel = 'Link copiado',
  className = 'model-source-back-btn',
  disabled = false,
  title = '',
}) {
  const [copied, setCopied] = useState(false)

  useEffect(() => {
    if (!copied) return undefined
    const timeoutId = window.setTimeout(() => setCopied(false), 1800)
    return () => window.clearTimeout(timeoutId)
  }, [copied])

  async function onCopyClick() {
    if (disabled || !href) return
    try {
      if (navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(href)
      } else {
        fallbackCopyText(href)
      }
      setCopied(true)
    } catch {
      fallbackCopyText(href)
      setCopied(true)
    }
  }

  return (
    <button
      type="button"
      className={className}
      onClick={() => void onCopyClick()}
      disabled={disabled || !href}
      title={title || href || 'Copiar link'}
    >
      {copied ? copiedLabel : label}
    </button>
  )
}
