'use client';

import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ReferenceLine } from 'recharts';
import { SprintVelocity } from '@/lib/types';

interface BurndownChartProps {
  sprintHistory: SprintVelocity[];
  className?: string;
}

interface BurndownDataPoint {
  day: string;
  remaining: number;
  ideal: number;
  actual: number;
}

export function BurndownChart({ sprintHistory, className }: BurndownChartProps) {
  // Générer des données de burndown simulées pour le sprint actuel
  const currentSprint = sprintHistory[sprintHistory.length - 1];
  
  if (!currentSprint) {
    return (
      <div className={`${className} flex items-center justify-center text-[var(--muted-foreground)]`}>
        Aucun sprint disponible pour le burndown
      </div>
    );
  }

  // Simuler une progression de burndown sur 14 jours (sprint de 2 semaines)
  const sprintDays = 14;
  const totalWork = currentSprint.plannedPoints;
  const completedWork = currentSprint.completedPoints;
  
  const burndownData: BurndownDataPoint[] = [];
  
  for (let day = 0; day <= sprintDays; day++) {
    const idealRemaining = totalWork - (totalWork * day / sprintDays);
    
    // Simuler une progression réaliste avec des variations
    let actualRemaining = totalWork;
    if (day > 0) {
      const progressRate = completedWork / totalWork;
      const expectedProgress = (totalWork * day / sprintDays) * progressRate;
      // Ajouter un peu de variation réaliste
      const variation = Math.sin(day * 0.3) * (totalWork * 0.05);
      actualRemaining = Math.max(0, totalWork - expectedProgress + variation);
    }
    
    burndownData.push({
      day: day === 0 ? 'Début' : day === sprintDays ? 'Fin' : `J${day}`,
      remaining: Math.round(actualRemaining * 10) / 10,
      ideal: Math.round(idealRemaining * 10) / 10,
      actual: Math.round(actualRemaining * 10) / 10
    });
  }

  const CustomTooltip = ({ active, payload, label }: { 
    active?: boolean; 
    payload?: Array<{ value: number; name: string; color: string }>; 
    label?: string 
  }) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 shadow-lg">
          <p className="font-medium text-sm mb-2">{label}</p>
          <div className="space-y-1 text-xs">
            {payload.map((item, index) => (
              <div key={index} className="flex justify-between gap-4">
                <span style={{ color: item.color }}>
                  {item.name === 'ideal' ? 'Idéal' : 'Réel'}:
                </span>
                <span className="font-mono" style={{ color: item.color }}>
                  {item.value} points
                </span>
              </div>
            ))}
          </div>
        </div>
      );
    }
    return null;
  };

  return (
    <div className={className}>
      {/* Graphique */}
      <div style={{ width: '100%', height: '240px' }}>
        <ResponsiveContainer width="100%" height="100%">
          <LineChart data={burndownData} margin={{ top: 20, right: 30, left: 20, bottom: 40 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
            <XAxis 
              dataKey="day" 
              stroke="var(--muted-foreground)"
              fontSize={12}
            />
            <YAxis 
              stroke="var(--muted-foreground)"
              fontSize={12}
              label={{ value: 'Points restants', angle: -90, position: 'insideLeft' }}
            />
            <Tooltip content={<CustomTooltip />} />
            
            {/* Ligne idéale de burndown */}
            <Line 
              type="monotone" 
              dataKey="ideal" 
              stroke="hsl(142, 76%, 36%)" 
              strokeWidth={2}
              strokeDasharray="5 5"
              dot={false}
              name="Idéal"
            />
            
            {/* Progression réelle */}
            <Line 
              type="monotone" 
              dataKey="actual" 
              stroke="hsl(217, 91%, 60%)" 
              strokeWidth={3}
              dot={{ fill: 'hsl(217, 91%, 60%)', strokeWidth: 2, r: 4 }}
              name="Réel"
            />
            
            {/* Ligne de référence à 0 */}
            <ReferenceLine y={0} stroke="var(--muted-foreground)" strokeDasharray="2 2" />
          </LineChart>
        </ResponsiveContainer>
      </div>
      
      {/* Légende visuelle */}
      <div className="mb-4 flex justify-center gap-6 text-sm">
        <div className="flex items-center gap-2">
          <div className="w-4 h-0.5 bg-green-500 border-dashed border-t-2 border-green-500"></div>
          <span className="text-green-500">Idéal</span>
        </div>
        <div className="flex items-center gap-2">
          <div className="w-4 h-0.5 bg-blue-500"></div>
          <span className="text-blue-500">Réel</span>
        </div>
      </div>
      
      {/* Métriques */}
      <div className="grid grid-cols-3 gap-4 text-center">
        <div>
          <div className="text-sm font-medium text-green-500">
            {currentSprint.plannedPoints}
          </div>
          <div className="text-xs text-[var(--muted-foreground)]">
            Points planifiés
          </div>
        </div>
        <div>
          <div className="text-sm font-medium text-blue-500">
            {currentSprint.completedPoints}
          </div>
          <div className="text-xs text-[var(--muted-foreground)]">
            Points complétés
          </div>
        </div>
        <div>
          <div className="text-sm font-medium text-orange-500">
            {currentSprint.completionRate}%
          </div>
          <div className="text-xs text-[var(--muted-foreground)]">
            Taux de réussite
          </div>
        </div>
      </div>
    </div>
  );
}
