import React from 'react';

// Utilisation de couleurs hexadécimales pour le SVG
const COLORS = [
  '#60a5fa', // bleu-400
  '#fb923c', // orange-400
  '#a78bfa', // violet-400
  '#34d399', // émeraude-400
];

export default function PieChart({ data }) {
  if (!data || data.length === 0) {
    return <div className="text-gray-400 text-center">Aucune donnée</div>;
  }

  const total = data.reduce((acc, d) => acc + d.value, 0);
  if (total === 0) {
    return <div className="text-gray-400 text-center">Aucune donnée</div>;
  }

  let cumulative = 0;

  return (
    <div className="flex items-center justify-center w-full">
      <svg width={100} height={100} viewBox="0 0 32 32">
        {data.map((slice, idx) => {
          if (slice.value === 0) return null;
          const value = (slice.value / total) * 100;
          if (value === 100) {
            // Cas 100% : on dessine un cercle plein
            return (
              <circle
                key={idx}
                cx="16"
                cy="16"
                r="16"
                fill={COLORS[idx % COLORS.length]}
              />
            );
          }
          const startAngle = (cumulative / 100) * 360;
          const endAngle = ((cumulative + value) / 100) * 360;
          const largeArc = value > 50 ? 1 : 0;
          const x1 = 16 + 16 * Math.cos((Math.PI * (startAngle - 90)) / 180);
          const y1 = 16 + 16 * Math.sin((Math.PI * (startAngle - 90)) / 180);
          const x2 = 16 + 16 * Math.cos((Math.PI * (endAngle - 90)) / 180);
          const y2 = 16 + 16 * Math.sin((Math.PI * (endAngle - 90)) / 180);
          const pathData = `
            M16,16
            L${x1},${y1}
            A16,16 0 ${largeArc} 1 ${x2},${y2}
            Z
          `;
          cumulative += value;
          return (
            <path
              key={idx}
              d={pathData}
              fill={COLORS[idx % COLORS.length]}
              stroke="#fff"
              strokeWidth="0.5"
            />
          );
        })}
      </svg>
      <div className="ml-4 flex flex-col space-y-1">
        {data.map((slice, idx) =>
          slice.value > 0 && (
            <div
              key={idx}
              className="flex items-center text-xs font-semibold"
              style={{ color: COLORS[idx % COLORS.length] }}
            >
              <span
                className="inline-block w-3 h-3 mr-2 rounded"
                style={{ backgroundColor: COLORS[idx % COLORS.length] }}
              />
              {slice.label} : {slice.value}
            </div>
          )
        )}
      </div>
    </div>
  );
}
