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

import { useAvatarStore } from "src/Stores";

export default observer(() => {
  const { dateSet, dateValues } = useAvatarStore();
  const dateView = useRef<HTMLCanvasElement>(null);

  const { t } = useTranslation();

  useEffect(() => {
    const view2D = dateView.current?.getContext("2d");
    if (view2D) {
      Chart.register(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>{t("avatarDateText")}</Badge>
      <ListGroupItem>
        <canvas ref={dateView} />
      </ListGroupItem>
    </ListGroup>
  );
});
