import React, { useEffect, useState } from 'react';
import ReactApexChart from "react-apexcharts";
import PropTypes from "prop-types";

const Chart = ReactApexChart.default || ReactApexChart;

function PieChart({ data, selectedValue, selectedValue3 }) {
  const [labelsData, setLabelsData] = useState([])
  const [seriesData, setSeriesData] = useState([])

  useEffect(() => {
    if (!data || data?.length === 0 || !data[0]?.Results?.length) return;
    
    const results = data[0].Results;
    const transformData = () => {
      const pieData = {
        "count": [],
        "labels": [],
      }
      switch (selectedValue) {
        case 'Sessions':
          results.forEach(item => {
            pieData.labels.push(item.SystemStatus);
            pieData.count.push(item.Count);
          });
          break;
        case 'Calls':
          results.forEach(item => {
            pieData.labels.push(item.EmpCode);
            pieData.count.push(item.CallsCount);
          });
          break;
        default:
          results.forEach(item => {
            pieData.labels.push(item.ApplicationName);
            pieData.count.push(item.ApplicationCount);
          });
      }
      return pieData
    };
    const chartData = transformData();
    setLabelsData(chartData.labels)
    setSeriesData(chartData.count)
    globalThis.dispatchEvent(new Event('resize'));
  }, [data, selectedValue, selectedValue3]);

  if (!data || data?.length === 0 || !data[0]?.Results?.length) {
    return <div>No Data found for selected filters</div>;
  }

  const options = {
    chart: {
      type: "donut",
      toolbar: {
        show: false,
      },
    },
    colors: ['#A300D6','#7D02EB','#5653FE','#2983FF','#00B1F2','#00D1B2','#00E0A3','#00F0A3','#00FF8C','#00FF5C'],
    labels: labelsData || [],
    responsive: [{
      breakpoint: 768,
      options: {
        chart: {
          width: '100%'
        },
        legend: {
          position: 'bottom'
        }
      }
    }]
  };
  
  return (
    <div style={{ height: "calc(100vh - 160px)", background: "#fff" }}>
      <Chart options={options} series={seriesData} type="donut" height="90%" width="100%" />
    </div>
  );
}

export default PieChart;

PieChart.propTypes = {
  data: PropTypes.arrayOf(PropTypes.shape({
    Results: PropTypes.array.isRequired
  })),
  selectedValue: PropTypes.string.isRequired,
  selectedValue3: PropTypes.string.isRequired,
};
