/* eslint-disable sort-imports */
/* eslint-disable import/order */
import React, { useRef, useEffect } from 'react';

import 'chartjs-adapter-moment';

import type { ScatterDataPoint } from 'chart.js';
import {
  Chart,
  Filler,
  Tooltip,
  TimeScale,
  LinearScale,
  LineElement,
  PointElement,
  LineController,
} from 'chart.js';

Chart.register(
  Filler,
  Tooltip,
  TimeScale,
  LineElement,
  LinearScale,
  PointElement,
  LineController
);

type ILineChart2Props = { data: any };

const LineChart2 = ({ data }: ILineChart2Props): JSX.Element => {
  const canvas = useRef<any>(null);
  const chartRef = useRef<Chart<
    'line',
    (number | ScatterDataPoint | null)[],
    unknown
  > | null>(null);

  useEffect(() => {
    const ctx = canvas.current;

    // Destroy existing chart instance if it exists
    if (chartRef.current) {
      chartRef.current.destroy();
    }

    // Create new chart instance
    chartRef.current = new Chart(ctx, {
      type: 'line',
      data: data,
      options: {
        borderColor: '#ffffff',
        layout: {
          padding: {
            top: 0,
            bottom: 0,
            left: 0,
            right: 0,
          },
        },
        scales: {
          y: {
            beginAtZero: false,
            grid: { drawTicks: true, color: '#ffffff' },
            ticks: { display: false },
          },
          x: {
            border: { color: '#ffffff' },
            display: false,
            grid: { lineWidth: 0 },
          },
        },
        plugins: {
          tooltip: {
            callbacks: { label: context => `${context.parsed.y}` },
          },
          legend: { display: false },
        },
        interaction: { intersect: false, mode: 'nearest' },
        maintainAspectRatio: false,
        responsive: true,
      },
    });

    // Cleanup function to destroy the chart instance
    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
        chartRef.current = null;
      }
    };
  }, [data]);

  return (
    // <div className="relative h-20 border-t md:border-t-0 w-[80vw] md:w-[40vw] lg:w-[30vw] xl:w-[15vw] 2xl:w-[18vw]">
    <div className="w-full h-10">
      <canvas ref={canvas} className="rounded-xl border-0"></canvas>
    </div>
  );
};

export default LineChart2;
