import React from 'react';

export default function GradesDomainBarChart({ studentCompetencies }) {
  if (!studentCompetencies?.data) return null;

  // Calcul du score moyen par domaine
  const domainStats = studentCompetencies.data.map((domaine) => {
    const allScores = domaine.categories.flatMap(
      (cat) =>
        cat.competences
          .map((comp) => comp.score ?? 0)
          .filter((score) => score > 0) // Ignorer les notes à 0
    );
    const avg =
      allScores.length > 0
        ? (allScores.reduce((a, b) => a + b, 0) / allScores.length).toFixed(2)
        : 0;
    return {
      name: domaine.domaine_nom,
      avg: Number(avg),
      count: allScores.length,
    };
  });

  // Détermine la couleur de la jauge selon la moyenne
  const getBarGradient = (avg) => {
    if (avg > 0 && avg <= 1) return 'bg-gradient-to-r from-red-200 to-red-400';
    if (avg > 1 && avg <= 2)
      return 'bg-gradient-to-r from-yellow-200 to-yellow-400';
    if (avg > 2) return 'bg-gradient-to-r from-primary/20 to-primary';
    return 'bg-gray-200';
  };

  return (
    <div className="w-full flex flex-col items-center gap-4 bg-stone-50 p-6 rounded-lg shadow-sm border border-gray-200">
      <h2 className="font-headline text-xl font-semibold mb-2">Moyenne par domaine</h2>
      <div className="w-full flex flex-col gap-2">
        {domainStats.map((d) => (
          <div key={d.name} className="flex items-center w-full">
            <span className="font-medium text-left" style={{ width: '30%' }}>
              {d.name}
            </span>
            <div className="flex items-center" style={{ width: '40%' }}>
              <div className="w-full bg-primary/10 h-3 rounded overflow-hidden">
                <div
                  className={`h-3 rounded ${getBarGradient(d.avg)}`}
                  style={{ width: `${d.avg * 33.33}%` }}
                />
              </div>
            </div>
            <span
              className="text-xs font-semibold text-secondary text-left pl-2 flex-shrink-0"
              style={{ width: '10%' }}
            >
              {d.avg}
            </span>
            <span className="text-gray-500 text-left" style={{ width: '20%' }}>
              ({`compétences évaluées ${d.count}`})
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}
