import {
  BarController,
  BarElement,
  CategoryScale,
  Chart,
  LinearScale,
  LineController,
} from "chart.js";
import { observer } from "mobx-react-lite";
import { useEffect, useRef } from "react";
import Card from "react-bootstrap/Card";
import CardBody from "react-bootstrap/CardBody";
import CardHeader from "react-bootstrap/CardHeader";

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 (
    <Card>
      <CardHeader>{title}</CardHeader>
      <CardBody>
        <canvas ref={dateView} />
      </CardBody>
    </Card>
  );
});
