/* eslint-disable import/no-named-as-default */
import React, { useEffect, useRef } from 'react';
import Chart from 'chart.js/auto';
import type { ChartType, ChartData, ChartOptions } from 'chart.js';

interface ChartCanvasProps {
  type: ChartType;
  data: ChartData;
  options?: ChartOptions;
  height?: number;
}

const ChartCanvas = ({
  type,
  data,
  options,
  height = 280,
}: ChartCanvasProps): JSX.Element => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const chartRef = useRef<Chart | null>(null);

  useEffect(() => {
    if (!canvasRef.current || !data) return;
    if (chartRef.current) chartRef.current.destroy();
    chartRef.current = new Chart(canvasRef.current, {
      type,
      data,
      options: { responsive: true, maintainAspectRatio: false, ...options },
    });
    return () => {
      if (chartRef.current) chartRef.current.destroy();
    };
  }, [type, data, options]);

  return (
    <div style={{ height }}>
      <canvas ref={canvasRef} />
    </div>
  );
};

export default ChartCanvas;
