import React, { useEffect, useRef } from 'react';
import Chart from 'chart.js/auto';

interface ChartCardProps {
  title: string;
  type: 'bar' | 'pie' | 'doughnut' | 'line';
  labels: string[];
  data: number[];
  backgroundColor?: string | string[];
  borderColor?: string | string[];
}

export default function ChartCard({ 
  title, 
  type, 
  labels, 
  data, 
  backgroundColor = '#3B82F6',
  borderColor = '#1E40AF'
}: ChartCardProps) {
  const chartRef = useRef<HTMLCanvasElement>(null);
  const chartInstance = useRef<Chart | null>(null);

  useEffect(() => {
    if (!chartRef.current) return;
    
    // Destroy existing chart if it exists
    if (chartInstance.current) {
      chartInstance.current.destroy();
    }
    
    const ctx = chartRef.current.getContext('2d');
    if (!ctx) return;

    // Create chart configuration based on chart type
    const config = {
      type,
      data: {
        labels,
        datasets: [
          {
            label: type === 'bar' || type === 'line' ? 'Number of Jumps' : undefined,
            data,
            backgroundColor,
            borderColor: type === 'bar' || type === 'line' ? borderColor : undefined,
            borderWidth: 1
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: type === 'pie' || type === 'doughnut',
            position: 'bottom' as const
          }
        },
        scales: type === 'bar' || type === 'line' ? {
          y: {
            beginAtZero: true
          }
        } : undefined
      }
    };

    // Create new chart
    chartInstance.current = new Chart(ctx, config);

    // Cleanup on unmount
    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
      }
    };
  }, [type, labels, data, backgroundColor, borderColor]);

  return (
    <div className="bg-white rounded-lg shadow p-6">
      <h3 className="text-lg font-medium text-gray-800 mb-4">{title}</h3>
      <div className="h-80">
        <canvas ref={chartRef}></canvas>
      </div>
    </div>
  );
}
