import { Doughnut } from 'react-chartjs-2';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { useRef, useMemo } from 'react';
import html2canvas from 'html2canvas';
import downi from '../assets/downi.png';

// Register all necessary components
ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels);

function DonutChart({ chartData }) {
  const chartRef = useRef(null);

  const data = useMemo(() => {
    if (!chartData || !chartData.labels?.length) {
      return { labels: [], datasets: [] };
    }
    return {
      labels: chartData.labels,
      datasets: [
        {
          label: 'Spend',
          data: chartData.values,
          backgroundColor: ['#6ECEB2', '#5450E4', '#69B8F7', '#FDBA74', '#F472B6'],
          borderColor: '#FFFFFF',
          borderWidth: 2,
        },
      ],
    };
  }, [chartData]);

  const options = {
    responsive: true,
    maintainAspectRatio: false,

    // --- FIX 1: Add padding to the chart layout ---
    // This ensures Chart.js reserves space within the canvas for the labels
    // that are drawn outside the donut, preventing them from being cut off.
    layout: {
      padding: {
        top: 20,
        bottom: 30, // Added extra padding at the bottom specifically for the bottom label
        left: 20,
        right: 20,
      }
    },

    plugins: {
      legend: {
        display: false, // Disable default legend
      },
      tooltip: {
        enabled: true,
        backgroundColor: '#333',
        titleColor: '#fff',
        bodyColor: '#fff',
        padding: 10,
        displayColors: false,
        callbacks: {
          title: (tooltipItems) => tooltipItems[0].label,
          label: (tooltipItem) => {
            const value = tooltipItem.raw || 0;
            let formattedValue;
            if (value >= 1000000) {
              formattedValue = `$${(value / 1000000).toFixed(1)}M`;
            } else if (value >= 1000) {
              // Improved formatting for K values
              formattedValue = `$${(value / 1000).toFixed(0)}K`;
            } else {
              // Handle values less than 1000
              formattedValue = `$${value.toFixed(0)}`;
            }
            return `Spend: ${formattedValue}`;
          },
        },
      },
      datalabels: {
        formatter: (value, context) => {
          const total = context.chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
          if (total === 0) return '';
          const percentage = (value / total * 100);
          const label = context.chart.data.labels[context.dataIndex];

          // --- FIX 2: Lower the threshold ---
          // Changed from > 2 to > 1 so that smaller slices are more likely to show labels
          return percentage > 1 ? `${label}: ${percentage.toFixed(0)}%` : '';
        },
        color: '#000000', // Black font color
        font: {
          weight: 'bold',
          size: 11, // Slightly increased font size for better readability
        },
        anchor: 'end', // Anchor at the end of the arc
        align: 'end', // Align labels radially outside the arc
        // --- FIX 3: Reduce the offset ---
        offset: 5, // Reduced from 10 to keep labels closer to the chart
        clip: false, // Allow labels to extend beyond the chart drawing area (but still inside the canvas padding)
        clamp: true, // Ensure the label tries to stay visible if possible
        padding: 3, // Slightly increased padding
        textAlign: 'center', // Center-align text
        backgroundColor: 'rgba(255, 255, 255, 0.8)', // Semi-transparent white background, slightly more opaque
        borderRadius: 3, // Rounded corners for background
      },
    },
    cutout: '65%', // Slightly reduced cutout for smaller chart
  };

  const handleDownload = () => {
    const chartElement = chartRef.current;
    if (!chartElement) return;

    // Hide download icon using visibility to prevent layout shift
    const icon = chartElement.querySelector('[data-download-icon]');
    if (icon) icon.style.visibility = 'hidden';

    html2canvas(chartElement, {
      backgroundColor: '#ffffff',
      scale: 2, // Use a higher scale for better resolution
    }).then((canvas) => {
      const link = document.createElement('a');
      link.download = 'DonutChart.png';
      link.href = canvas.toDataURL('image/png');
      link.click();
      // Restore visibility
      if (icon) icon.style.visibility = 'visible';
    }).catch((error) => {
      console.error('Error generating image:', error);
      alert('Failed to download chart as image');
      // Restore visibility even on error
      if (icon) icon.style.visibility = 'visible';
    });
  };

  // Check if there's actually any data to display (sum > 0)
  const hasData = data.datasets.length > 0 && data.datasets[0].data.length > 0 && data.datasets[0].data.some(v => v > 0);

  return (
    <div className="p-3 bg-white rounded-lg border-1.25 border-grey shadow h-full flex flex-col" ref={chartRef}>
      <div className="flex justify-between items-center mb-2">
        <h3 className="text-sm font-semibold text-black">Spend by Category</h3>
        <button onClick={handleDownload} className="hover:bg-gray-200 p-1 rounded-full">
          <img src={downi} alt="Download Icon" className="w-6 h-6 object-contain" data-download-icon />
        </button>
      </div>

      {/* --- FIX 4: Increase container height --- */}
      {/* Changed h-40 (160px) to h-56 (224px) to give the canvas more vertical room. */}
      {/* Added flex-grow in case the parent is taller. */}
      <div className="h-56 relative flex-grow">
        {hasData ? (
          <Doughnut
            data={data}
            options={options}
          />
        ) : (
          <div className="flex items-center justify-center h-full text-gray-500">
            No Data Available
          </div>
        )}
      </div>
    </div>
  );
}

export default DonutChart;

need to add a small color for the particular category as a legend before the actual label to indicate the color