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

const GROUPS = [
  { key: 'visual_apresentacao', label: 'Formato para Apresentação', canExport: false },
  { key: 'excel', label: 'Formato Excel', canExport: true, exportMode: 'excel' },
  { key: 'excel_sab', label: 'Formato Excel (estilo SAB)', canExport: true, exportMode: 'excel_sab' },
]

function fallbackCopy(text) {
  const area = document.createElement('textarea')
  area.value = text
  area.setAttribute('readonly', '')
  area.style.position = 'fixed'
  area.style.opacity = '0'
  area.style.pointerEvents = 'none'
  document.body.appendChild(area)
  area.focus()
  area.select()
  try {
    document.execCommand('copy')
  } finally {
    area.remove()
  }
}

async function copyText(text) {
  const value = String(text || '').trim()
  if (!value) return false
  try {
    if (navigator?.clipboard?.writeText) {
      await navigator.clipboard.writeText(value)
      return true
    }
  } catch {
    // fallback below
  }
  try {
    fallbackCopy(value)
    return true
  } catch {
    return false
  }
}

export default function EquationFormatsPanel({ equacoes, onDownload, disabled = false }) {
  const [lastCopied, setLastCopied] = useState('')
  const groups = useMemo(() => GROUPS, [])

  async function onCopy(value, key) {
    const ok = await copyText(value)
    setLastCopied(ok ? key : '')
    if (ok) {
      window.setTimeout(() => setLastCopied(''), 1800)
    }
  }

  return (
    <div className="equation-formats-wrap">
      {groups.map((group) => {
        const value = String(equacoes?.[group.key] || '').trim()
        const hasValue = Boolean(value)
        return (
          <div key={group.key} className="equation-format-card">
            <div className="equation-format-head">
              <h5>{group.label}</h5>
              {group.canExport ? (
                <div className="equation-format-actions">
                  <button
                    type="button"
                    className="btn-download-subtle"
                    onClick={() => void onCopy(value, group.key)}
                    disabled={disabled || !hasValue}
                  >
                    {lastCopied === group.key ? 'Copiado' : 'Copiar fórmula'}
                  </button>
                  <button
                    type="button"
                    className="btn-download-subtle"
                    onClick={() => onDownload?.(group.exportMode)}
                    disabled={disabled || !hasValue || typeof onDownload !== 'function'}
                  >
                    Baixar Excel
                  </button>
                </div>
              ) : null}
            </div>
            <div className="equation-box equation-box-plain">
              {hasValue ? value : 'Equação indisponível.'}
            </div>
          </div>
        )
      })}
    </div>
  )
}

