import { useTranslationContext } from "@gnu-taler/web-util/browser";
import { ChartData, ChartOptions } from "chart.js";
import { h, VNode } from "preact";
import { useEffect, useRef } from "preact/hooks";
import {
  BarController,
  BarElement,
  CategoryScale,
  Chart,
  Filler,
  Legend,
  LinearScale,
  LineController,
  LineElement,
  PointElement,
  TimeScale,
  Title,
  Tooltip,
} from "chart.js";

Chart.register(
  CategoryScale,
  LinearScale,
  TimeScale,
  LineElement,
  PointElement,
  BarElement,
  BarController,
  LineController,
  Title,
  Filler,
  Tooltip,
  Legend,
);

/**
 *
 * @param param0
 * @returns
 */
export function BarCanvas({
  data,
  options,
}: {
  data: ChartData<"bar", unknown, unknown>;
  options: ChartOptions<"bar">;
}): VNode {
  const { i18n } = useTranslationContext();
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const chartRef = useRef<Chart<"bar", unknown, unknown> | null>(null);

  useEffect(() => {
    if (!canvasRef.current) return;
    chartRef.current = new Chart(canvasRef.current, {
      type: "bar" as const,
      data,
      options,
    });

    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
      }
    };
  }, []);

  useEffect(() => {
    if (!chartRef.current) {
      return;
    }
    chartRef.current.data = data;
    chartRef.current.options = options;
    chartRef.current.update();
  }, [data, options]);

  return (
    <canvas ref={canvasRef} role="img">
      <i18n.Translate>
        Your browser does not support the canvas element.
      </i18n.Translate>
    </canvas>
  );
}

export function LineCanvas({
  data,
  options,
}: {
  data: ChartData<"line", unknown, unknown>;
  options: ChartOptions<"line">;
}): VNode {
  const { i18n } = useTranslationContext();
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const chartRef = useRef<Chart<"line", unknown, unknown> | null>(null);

  useEffect(() => {
    if (!canvasRef.current) return;
    chartRef.current = new Chart(canvasRef.current, {
      type: "line" as const,
      data,
      options,
      plugins: [],
    });

    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
      }
    };
  }, []);

  return (
    <canvas ref={canvasRef} role="img">
      <i18n.Translate>
        Your browser does not support the canvas element.
      </i18n.Translate>
    </canvas>
  );
}
