import React, { useState, useLayoutEffect } from 'react';
import PropTypes from 'prop-types';
import ApexCharts from 'react-apexcharts';

const Chart = ApexCharts.default || ApexCharts;

export default function ChartComponent({ graphData }) {
  const [datas, setDatas] = useState([]);

  const updatedGraphData = graphData?.map(entry => {
    const timeOnly = entry.EndTime?.split('T')[1]?.slice(0, 5); // Keep only HH:MM
    return {
      ...entry,
      EndTime: timeOnly
    };
  });

  useLayoutEffect(() => {
    if (updatedGraphData?.length > 0) {
      let lineData = {
        ActiveLoginCount: [],
        loginCount: [],
        timeSeries: [],
      };
      updatedGraphData.forEach(item => {
        lineData.timeSeries.push(item.EndTime);
        lineData.ActiveLoginCount.push(item.ActiveLoginCount || 0);
        lineData.loginCount.push(item.LoginCount || 0);
      });
      setDatas(lineData);
    }
  }, [graphData]);

  const series = [
    { name: "Active Login Count", data: datas?.ActiveLoginCount || [0] },
    { name: "Login Count", data: datas?.loginCount || [0] }
  ];

  const options = {
    chart: { height: 350, type: 'line', zoom: { enabled: true }, toolbar: { show: true } },
    dataLabels: { enabled: false },
    colors: ['#ff7b00', '#84C484'],
    stroke: { curve: 'straight', width: 3 },
    xaxis: { categories: datas.timeSeries || [] },
    legend: { position: 'bottom' }
  };

  return (
    <div id="chart">
      <Chart options={options} series={series} type="line" height={350} />
    </div>
  );
}


ChartComponent.propTypes = {
  graphData: PropTypes.arrayOf(
    PropTypes.shape({
      EndTime: PropTypes.string,
      ActiveLoginCount: PropTypes.number,
      LoginCount: PropTypes.number
    })
  )
};


ChartComponent.defaultProps = {
  graphData: []
};
