import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'

const PieChart = ({ className, value, color, remainingValue = 100 }) => {
  const chartRef = useRef(null)

  useEffect(() => {
    const chartInstance = echarts.init(chartRef.current)

    // Check if both values are 0
    const isEmptyChart = value === 0 && remainingValue === 0

    const options = {
      title: {
        show: false
      },
      tooltip: {
        show: false
      },
      series: [
        {
          type: 'pie',
          top: 10,
          left: 10,
          right: 10,
          bottom: 10,
          radius: '100%',
          avoidLabelOverlap: false,
          label: {
            show: false
          },
          labelLine: {
            show: false
          },
          data: isEmptyChart
            ? [{ value: 1, name: 'Empty', itemStyle: { color: '#E0E0E0' } }]
            : [
                {
                  value: value,
                  name: 'Completed',
                  itemStyle: { color: color || '#FF6B6B' }
                },
                {
                  value: remainingValue - value,
                  name: 'Remaining',
                  itemStyle: { color: '#E0E0E0' }
                }
              ]
        }
      ]
    }

    chartInstance.setOption(options)

    return () => {
      chartInstance.dispose()
    }
  }, [value, color, remainingValue])

  return (
    <div
      ref={chartRef}
      className={`arcm-pie-chart ${
        className || 'arcm-h-[163px] arcm-w-[173px]'
      }`}
    ></div>
  )
}

export default PieChart
