interface SliceData {
  label: string;
  count: number;
}

interface PiechartProps {
  data: SliceData[];
  title?: string;
}

const COLORS = [
  '#3b82f6', '#10b981', '#f59e0b', '#ef4444',
  '#8b5cf6', '#ec4899', '#14b8a6', '#f97316',
];

function polarToCartesian(cx: number, cy: number, r: number, angleDeg: number) {
  const rad = ((angleDeg - 90) * Math.PI) / 180;
  return { x: cx + r * Math.cos(rad), y: cy + r * Math.sin(rad) };
}

function slicePath(cx: number, cy: number, r: number, startAngle: number, endAngle: number) {
  const start = polarToCartesian(cx, cy, r, startAngle);
  const end = polarToCartesian(cx, cy, r, endAngle);
  const largeArc = endAngle - startAngle > 180 ? 1 : 0;
  return `M ${cx} ${cy} L ${start.x} ${start.y} A ${r} ${r} 0 ${largeArc} 1 ${end.x} ${end.y} Z`;
}

export default function Piechart({ data, title }: PiechartProps) {
  const total = data.reduce((sum, d) => sum + d.count, 0);
  if (total === 0) return null;

  let currentAngle = 0;
  const slices = data.map((d, i) => {
    const angle = (d.count / total) * 360;
    const start = currentAngle;
    const end = currentAngle + angle;
    currentAngle = end;
    return { ...d, startAngle: start, endAngle: end, color: COLORS[i % COLORS.length] };
  });

  return (
    <div className="flex flex-col items-center gap-4">
      {title && <h3 className="text-sm font-semibold text-gray-600 uppercase tracking-wide">{title}</h3>}
      <div className="flex flex-col sm:flex-row items-center gap-6">
        <svg width="180" height="180" viewBox="0 0 200 200">
          {slices.map((s) => (
            <path
              key={s.label}
              d={slicePath(100, 100, 90, s.startAngle, s.endAngle)}
              fill={s.color}
              stroke="white"
              strokeWidth="2"
            >
              <title>{s.label}: {s.count}</title>
            </path>
          ))}
        </svg>
        <ul className="space-y-2">
          {slices.map((s) => (
            <li key={s.label} className="flex items-center gap-2 text-sm">
              <span
                className="w-3 h-3 rounded-full flex-shrink-0"
                style={{ backgroundColor: s.color }}
              />
              <span className="text-gray-700 capitalize">{s.label}</span>
              <span className="text-gray-400 ml-1">({s.count})</span>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
