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

import { GetAvatar } from "src/avatar/useGetAvatar";

export default function DateView({
  avatar: { dateSet, dateValues },
}: {
  avatar: GetAvatar;
}) {
  const dateView = useRef<HTMLCanvasElement>(null);

  const { t } = useTranslation();

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

      const view = new Chart(dateView2D, {
        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>
  );
}
