import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import type { SessionDebriefRow } from '../../types';
import { useI18n } from '../../i18n/context';

interface PrecisionChartProps {
  debriefRows: SessionDebriefRow[];
}

function PrecisionChart({ debriefRows }: PrecisionChartProps) {
  const { t, lang } = useI18n();

  // Group by sessionId and compute averages per session
  const bySession = new Map<number, { date: string; precisions: number[]; reactions: number[] }>();

  debriefRows.forEach((row) => {
    if (!bySession.has(row.sessionId)) {
      bySession.set(row.sessionId, { date: row.sessionDate, precisions: [], reactions: [] });
    }
    const entry = bySession.get(row.sessionId)!;
    if (row.hitPrecision > 0) entry.precisions.push(row.hitPrecision);
    if (row.reactionTime > 0) entry.reactions.push(row.reactionTime);
  });

  const data = Array.from(bySession.entries())
    .map(([, val]) => {
      const avgPrec = val.precisions.length > 0
        ? Math.round((val.precisions.reduce((a, b) => a + b, 0) / val.precisions.length) * 100) / 100
        : 0;
      const avgReact = val.reactions.length > 0
        ? Math.round(val.reactions.reduce((a, b) => a + b, 0) / val.reactions.length)
        : 0;
      return {
        date: val.date,
        dateLabel: new Date(val.date).toLocaleDateString(lang === 'fr' ? 'fr-FR' : 'en-US', { day: '2-digit', month: '2-digit' }),
        precision: avgPrec,
        reactionTime: avgReact,
      };
    })
    .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

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

  return (
    <ResponsiveContainer width="100%" height={300}>
      <LineChart data={data}>
        <CartesianGrid strokeDasharray="3 3" stroke="#333" />
        <XAxis dataKey="dateLabel" stroke="#888" />
        <YAxis yAxisId="left" stroke="#4a90d9" />
        <YAxis yAxisId="right" orientation="right" stroke="#f39c12" />
        <Tooltip
          contentStyle={{ backgroundColor: '#1a1a2e', border: '1px solid #333' }}
          labelFormatter={(label) => label}
        />
        <Legend />
        <Line yAxisId="left" type="monotone" dataKey="precision" stroke="#4a90d9" name={t('chart.precision')} strokeWidth={2} dot={{ r: 3 }} />
        <Line yAxisId="right" type="monotone" dataKey="reactionTime" stroke="#f39c12" name={t('chart.reactionTime')} strokeWidth={2} dot={{ r: 3 }} />
      </LineChart>
    </ResponsiveContainer>
  );
}

export default PrecisionChart;
