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

const Chart = ReactApexChart.default || ReactApexChart;

function BarChartStack({ data, selectedValue , selectedValue3 }) {
  const [seriesData, setSeriesData] = useState([])
  const [xData, setXData] = useState([])
  useEffect(() => {
    if (!data || !Array.isArray(data) || !data[0]?.Results) {
      return;
    }

    // Extract Results from data
    const results = data[0].Results;

    // Transform data to match chart format
    const transformedData = {
      date: [],
      active: [],
      idle: [],
      sleep: [],
      calls: [],
      applications: []
    }
    if (selectedValue === 'Sessions') {
      results.forEach((item) => {
        transformedData.date.push(new Date(item.LoginDate).getTime());
        transformedData.active.push(item.ActiveCount);
        transformedData.sleep.push(item.SleepCount);
        transformedData.idle.push(item.IdleCount);
      });
      setSeriesData([
        {name: "Active", data: transformedData.active},
        {name: "Idle", data: transformedData.idle},
        {name: "Sleep", data: transformedData.sleep}
      ])
      setXData(transformedData.date)
    } else if (selectedValue === 'Calls') {
      results.forEach((item) => {
        transformedData.date.push(new Date(item.StartedOn).getTime());
        transformedData.calls.push(item.CallsCount);
      });
      setSeriesData([
        {name: "Calls", data: transformedData.calls}
      ])
      setXData(transformedData.date)
    } else {
      results.forEach((item) => {
        transformedData.date.push(new Date(item.StartedOn).getTime());
        transformedData.applications.push(item.ApplicationCount);
      });
      setSeriesData([
        {name: "Applications", data: transformedData.applications}
      ])
      setXData(transformedData.date)
    } 
  }, [data, selectedValue]);

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

  const categoriesData = xData?.map(dateStr =>
    new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
  );

  const options = {
    chart: {
      type: "bar",
      stacked: selectedValue === 'Sessions',
      zoom: {
        enabled: true, type: 'xy',
      },
      toolbar: {
        show: true,
        tools: {
          zoom: true,
          zoomin: true,
          zoomout: true,
          pan: true,
          reset: true
        }
      }
    },
    colors: ['#A300D6','#2983FF','#00B1F2'],
    dataLabels: { enabled: false },
    responsive: [{
      breakpoint: 480,
      options: {
        legend: { position: "bottom" },
      },
    }],
    plotOptions: {
      bar: { horizontal: false, borderRadius: 4 }
    },
    xaxis: { categories: categoriesData },
    legend: { position: "bottom", offsetY: 40 },
    fill: { opacity: 1 },
    tooltip: {
      shared: false,
      intersect: false,
      custom ({ series, seriesIndex, dataPointIndex, w }) {
        let tooltipContent = '';
        let total = 0;
        for (let i = 0; i < series?.length; i++) {
          const value = series[i][dataPointIndex];
          total += value;
          const name = w.globals.seriesNames[i];
    
          tooltipContent += `${name}: ${String(value).padStart(6)}\n`;
        }
        tooltipContent += `\n${'Total'}: ${String(total).padStart(6)}`;
        return tooltipContent;
      }
    }
  };

  return (
    <div className="barstack-chart" style={{ height: "calc(100vh - 180px)", width: "100%", background: "#fff" }}>
      <Chart
        options={options}
        series={seriesData}
        type="bar"
        height="100%"
      />
    </div>

  );
}

export default BarChartStack;

BarChartStack.propTypes = {
  data: PropTypes.object.isRequired,
  selectedValue: PropTypes.string.isRequired,
  selectedValue3: PropTypes.string.isRequired,
};
