import Chart from 'chart.js/auto'

const { h, register, preactHooks, matter } = globalThis.ami
const { Box, Heading } = matter
const { useRef, useEffect, useState, useLayoutEffect } = preactHooks

function SimpleChart ({ src, title, subtitle }) {
  const [data, setData] = useState()
  const chart = useRef(null)
  const canvasRef = useRef(null)

  useEffect(() => {
    (async () => {
      const res = await fetch(src)
      setData(await res.json())
    })().catch(console.error)
  }, [src])

  useLayoutEffect(() => {
    if (!data || !canvasRef.current) {
      return
    }

    chart.current?.destroy()
    chart.current = new Chart(canvasRef.current, {
      ...data,
      options: {
        ...data.options,
        animation: {
          ...data.options?.animation,
          onComplete: () => canvasRef.current?.setAttribute('data-complete', '')
        }
      }
    })
  }, [data])

  if (!data) {
    return null
  }

  return h(Box, { className: 'bg-bga text-txa rounded-2xl' },
    h(Heading, { _level: 3 }, title),
    h('canvas', {
      className: 'w-full',
      ref: canvasRef,
      'aria-label': subtitle ? `${title}: ${subtitle}` : title,
      role: 'img'
    }),
    subtitle ? h('p', subtitle) : null
  )
}

register(SimpleChart, 'simple-chart')
