import React from 'react'
import Plot from 'react-plotly.js'
import Plotly from 'plotly.js-dist-min'

function PlotFigure({ figure, title, forceHideLegend = false, className = '' }) {
  if (!figure) {
    return <div className="empty-box">Grafico indisponivel.</div>
  }

  const data = (figure.data || []).map((trace) => {
    if (!forceHideLegend) return trace
    return { ...trace, showlegend: false }
  })

  const baseLayout = figure.layout || {}
  const { width: _ignoreWidth, ...layoutNoWidth } = baseLayout
  const safeAnnotations = Array.isArray(baseLayout.annotations)
    ? baseLayout.annotations.map((annotation) => {
        const { ax, ay, axref, ayref, arrowhead, arrowsize, arrowwidth, arrowcolor, standoff, ...clean } = annotation || {}
        return { ...clean, showarrow: false }
      })
    : baseLayout.annotations
  const layout = {
    ...layoutNoWidth,
    autosize: true,
    annotations: safeAnnotations,
    margin: baseLayout.margin || { t: 40, r: 20, b: 50, l: 50 },
  }
  if (forceHideLegend) {
    layout.showlegend = false
  }
  const plotHeight = layout.height ? `${layout.height}px` : '100%'
  const cardClassName = `plot-card ${className}`.trim()

  return (
    <div className={cardClassName}>
      {title ? <h4>{title}</h4> : null}
      <Plot
        data={data}
        layout={layout}
        config={{ responsive: true, displaylogo: false }}
        style={{ width: '100%', height: plotHeight, minHeight: '320px' }}
        useResizeHandler
        plotly={Plotly}
      />
    </div>
  )
}

export default React.memo(PlotFigure)
