import React from 'react';
import { Line } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';

// ✅ Register Chart.js components
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend);

// ✅ Default stock data (used if no data is passed)
const defaultStockData = [
  { date: '2024-03-01', price: 120 },
  { date: '2024-03-02', price: 125 },
  { date: '2024-03-03', price: 130 },
  { date: '2024-03-04', price: 128 },
  { date: '2024-03-05', price: 135 },
];

const FinancialChart = ({ data }) => {
  // ✅ Use default data if no data is provided
  const stockData = data && data.length > 0 ? data : defaultStockData;

  const chartData = {
    labels: stockData.map(item => item.date), // X-axis labels (dates)
    datasets: [
      {
        label: 'Stock Price',
        data: stockData.map(item => item.price), // Y-axis values (prices)
        borderColor: 'rgba(75, 192, 192, 1)',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        fill: true,
      },
    ],
  };

  const chartOptions = {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Financial Data Chart',
      },
      tooltip: {
        callbacks: {
          label: (tooltipItem) => `$${tooltipItem.raw.toFixed(2)}`,
        },
      },
    },
    scales: {
      x: {
        title: {
          display: true,
          text: 'Date',
        },
      },
      y: {
        title: {
          display: true,
          text: 'Price (USD)',
        },
        ticks: {
          callback: (value) => `$${value.toFixed(2)}`,
        },
      },
    },
  };

  return <Line data={chartData} options={chartOptions} />;
};

export default FinancialChart;
