import { useEffect, useRef } from "react";
import { observer } from "mobx-react-lite";
import {
  BarController,
  BarElement,
  CategoryScale,
  Chart,
  LinearScale,
  LineController,
} from "chart.js";
import { Badge, ListGroup, ListGroupItem } from "reactstrap";

export default observer<{
  title: string;
  dateSet: string[];
  dateValues: number[];
}>(({ title, dateSet, dateValues }) => {
  const dateView = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const view2D = dateView.current?.getContext("2d");
    if (view2D) {
      Chart.register(
        LineController,
        BarController,
        BarElement,
        CategoryScale,
        LinearScale,
      );

      const view = new Chart(view2D, {
        type: "bar",
        data: {
          labels: dateSet,
          datasets: [
            {
              data: dateValues,
              backgroundColor: "white",
            },
          ],
        },
        options: {
          scales: {
            x: {
              display: false,
            },
            y: {
              display: false,
            },
          },
        },
      });

      return () => {
        view.destroy();
        Chart.unregister(BarController, BarElement, CategoryScale, LinearScale);
      };
    }
  }, [dateSet, dateValues]);

  return (
    <ListGroup>
      <Badge color="primary">{title}</Badge>
      <ListGroupItem>
        <canvas ref={dateView} />
      </ListGroupItem>
    </ListGroup>
  );
});
