import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { SESSION_TYPE_LABELS, SESSION_TYPE_COLORS } from '../../types';
import type { Session } from '../../types';

interface SessionsByTypeChartProps {
  sessions: Session[];
  onSliceClick?: (typeId: number) => void;
}

function SessionsByTypeChart({ sessions, onSliceClick }: SessionsByTypeChartProps) {
  const countByType: Record<number, number> = {};
  sessions.forEach((s) => {
    countByType[s.sessionTypeAsInt] = (countByType[s.sessionTypeAsInt] || 0) + 1;
  });

  const data = Object.entries(countByType).map(([typeId, count]) => ({
    name: SESSION_TYPE_LABELS[Number(typeId)] || `Type ${typeId}`,
    value: count,
    color: SESSION_TYPE_COLORS[Number(typeId)] || '#6c757d',
    typeId: Number(typeId),
  }));

  if (data.length === 0) return <p className="text-muted-custom text-center">Aucune donnée</p>;

  return (
    <ResponsiveContainer width="100%" height={300}>
      <PieChart>
        <Pie
          data={data}
          dataKey="value"
          nameKey="name"
          cx="50%"
          cy="50%"
          outerRadius={100}
          label
          style={onSliceClick ? { cursor: 'pointer' } : undefined}
          onClick={onSliceClick ? (_data: unknown, index: number) => onSliceClick(data[index].typeId) : undefined}
        >
          {data.map((entry, index) => (
            <Cell key={index} fill={entry.color} />
          ))}
        </Pie>
        <Tooltip contentStyle={{ backgroundColor: '#1a1a2e', border: '1px solid #333' }} />
        <Legend />
      </PieChart>
    </ResponsiveContainer>
  );
}

export default SessionsByTypeChart;
