import React from 'react';

const COLORS = [
  'fill-blue-400 text-blue-400',
  'fill-orange-400 text-orange-400',
  'fill-purple-400 text-purple-400',
  'fill-emerald-400 text-emerald-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) => {
          const value = (slice.value / total) * 100;
          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}
              className={COLORS[idx % COLORS.length].split(' ')[0]}
              stroke="#fff"
              strokeWidth="0.5"
            />
          );
        })}
      </svg>
      <div className="ml-4 flex flex-col space-y-1">
        {data.map((slice, idx) => (
          <div
            key={idx}
            className={`flex items-center text-xs font-semibold ${COLORS[idx % COLORS.length].split(' ')[1]}`}
          >
            <span
              className={`inline-block w-3 h-3 mr-2 rounded ${COLORS[idx % COLORS.length].split(' ')[0]}`}
            />
            {slice.label} : {slice.value}
          </div>
        ))}
      </div>
    </div>
  );
}
