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

const Card = ({ name, icon, value }) => {
  const canvasRef = useRef(null);
  const chartRef = useRef(null);

  // Helper function to simulate a linear progression from 0 to value
  const simulateData = (value) => {
    const steps = 6; // Adjust number of data points as needed
    const data = [];
    for (let i = 0; i < steps; i++) {
      data.push((value / (steps - 1)) * i);
    }
    return data;
  };

  useEffect(() => {
    // Clean up any existing chart instance before creating a new one
    if (chartRef.current) {
      chartRef.current.destroy();
    }

    if (canvasRef.current) {
      const ctx = canvasRef.current.getContext("2d");
      const simulatedData = simulateData(value);

      chartRef.current = new Chart(ctx, {
        type: "line",
        data: {
          // Placeholder labels; can be customized if needed
          labels: ["", "", "", "", "", ""],
          datasets: [
            {
              label: name,
              data: simulatedData,
              borderColor: "#4CAF50",
              backgroundColor: "rgba(76, 175, 80, 0.2)",
              borderWidth: 2,
              fill: true,
            },
          ],
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            x: {
              display: false,
            },
            y: {
              display: false,
              beginAtZero: true, // Ensures the scale starts at 0
              min: 0,
            },
          },
          plugins: {
            legend: {
              display: false,
            },
          },
        },
      });
    }

    // Cleanup on component unmount or before re-running effect
    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
        chartRef.current = null;
      }
    };
  }, [value, name]);

  return (
    <div className="col-md-4">
      <div className="single-report">
        <div className="s-report-inner pr--20 pt--30 mb-3">
          <div className="icon">
            <i className={`fa ${icon}`}></i>
          </div>
          <div className="s-report-title">
            <h4 className="header-title mb-0">{name}</h4>
          </div>
          <div className="d-flex justify-content-between pb-2">
            <h2>{value.toLocaleString()}</h2>
          </div>
        </div>
        {/* 
          The wrapping div should have a defined height in your CSS,
          so the canvas can automatically take 100% of the available space.
        */}
        <div style={{ width: "100%", height: "100%" }}>
          <canvas
            ref={canvasRef}
            style={{
              display: "block",
              width: "100%",
              height: "100%",
            }}
          ></canvas>
        </div>
      </div>
    </div>
  );
};

export default Card;
