import * as React from 'react';
import { BarChart } from '@mui/x-charts/BarChart';
import { useSelector } from 'react-redux';
import { getWebSocket } from '../../redux/selectors';
import axios from 'axios';

const chartSetting = {
  xAxis: [
    {
      label: 'Drugs By Company'
    }
  ],
  width: 500,
  height: 400
};
type data = { manufacturer: string; count: number };

// const dataset: data[] = [];
// drugs.forEach((drug) => {
//   const manufacturer = drug.manufacturer;
//   const index = dataset.findIndex((data) => data.manufacturer === manufacturer);
//   if (index === -1) {
//     dataset.push({ manufacturer, count: 1 });
//   } else {
//     dataset[index].count++;
//   }
// });

const valueFormatter = (value: number) => `${value} #`;

export default function DrugBarChart() {
  const ws = useSelector(getWebSocket);
  const [data, setData] = React.useState<data[]>([]);
  const [newitems, setNewItems] = React.useState<number>(1);

  const fetchData = async () => {
    const data = await axios.get(
      'https://silkroadapi.azurewebsites.net/Drug/get-chart-data',
      { withCredentials: true }
    );
    setData(data.data);
    setNewItems(0);
  };

  React.useEffect(() => {
    ws?.addEventListener('message', (event) => {
      console.log(event.data);
      setNewItems(1);
      fetchData();
    });
  }, [ws]);

  React.useEffect(() => {
    if (newitems === 0) return;
    fetchData();
    console.log(data);
  }, [data, newitems]);

  // const groupBy = () => {
  //   const dataset: data[] = [];
  //   const arrayDrug = [...drugs];
  //   arrayDrug.forEach((drug: Drug) => {
  //     const manufacturer = drug.manufacturer;
  //     const index = dataset.findIndex(
  //       (data) => data.manufacturer === manufacturer
  //     );
  //     if (index === -1) {
  //       dataset.push({ manufacturer, count: 1 });
  //     } else {
  //       dataset[index].count++;
  //     }
  //   });
  //   return dataset;
  // };

  // const [dataset] = React.useState<data[]>(groupBy());
  console.log(data);
  return (
    data.length > 0 && (
      <BarChart
        dataset={data}
        yAxis={[{ scaleType: 'band', dataKey: 'manufacturer' }]}
        series={[{ dataKey: 'count', label: 'Total Drugs', valueFormatter }]}
        layout='horizontal'
        {...chartSetting}
      />
    )
  );
}
