import { GetAvatar } from "@/app/[language]/avatar/query/useGetAvatar";
import {
  BarController,
  BarElement,
  CategoryScale,
  Chart,
  LinearScale,
} from "chart.js";
import { useTranslations } from "next-intl";
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 function DateView({
  avatar: { dateSet, dateValues },
}: {
  avatar: GetAvatar;
}) {
  const dateView = useRef<HTMLCanvasElement>(null);

  const t = useTranslations();

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