'use client';

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

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

interface ThroughputDataPoint {
  period: string;
  completed: number;
  planned: number;
  throughput: number; // Tickets par jour
  trend: number; // Moyenne mobile
}

export function ThroughputChart({
  sprintHistory,
  className,
}: ThroughputChartProps) {
  // Calculer les données de throughput
  const throughputData: ThroughputDataPoint[] = sprintHistory.map(
    (sprint, index) => {
      const sprintDuration = 14; // 14 jours de travail par sprint
      const throughput =
        Math.round((sprint.completedPoints / sprintDuration) * 10) / 10;

      // Calculer la moyenne mobile sur les 3 derniers sprints
      const windowStart = Math.max(0, index - 2);
      const window = sprintHistory.slice(windowStart, index + 1);
      const avgThroughput =
        window.reduce((sum, s) => sum + s.completedPoints / sprintDuration, 0) /
        window.length;

      return {
        period: sprint.sprintName.replace('Sprint ', ''),
        completed: sprint.completedPoints,
        planned: sprint.plannedPoints,
        throughput: throughput,
        trend: Math.round(avgThroughput * 10) / 10,
      };
    }
  );

  const maxThroughput = Math.max(...throughputData.map((d) => d.throughput));
  const avgThroughput =
    throughputData.reduce((sum, d) => sum + d.throughput, 0) /
    throughputData.length;

  const CustomTooltip = ({
    active,
    payload,
    label,
  }: {
    active?: boolean;
    payload?: Array<{
      payload: ThroughputDataPoint;
      value: number;
      name: string;
      color: string;
      dataKey: string;
    }>;
    label?: string;
  }) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload;
      return (
        <div className="bg-[var(--card)] border border-[var(--border)] rounded-lg p-3 shadow-lg">
          <p className="font-medium text-sm mb-2">Sprint {label}</p>
          <div className="space-y-1 text-xs">
            <div className="flex justify-between gap-4">
              <span>Complétés:</span>
              <span className="font-mono text-blue-500">
                {data.completed} points
              </span>
            </div>
            <div className="flex justify-between gap-4">
              <span>Planifiés:</span>
              <span className="font-mono text-gray-500">
                {data.planned} points
              </span>
            </div>
            <div className="flex justify-between gap-4">
              <span>Throughput:</span>
              <span className="font-mono text-green-500">
                {data.throughput} pts/jour
              </span>
            </div>
            <div className="flex justify-between gap-4">
              <span>Tendance:</span>
              <span className="font-mono text-orange-500">
                {data.trend} pts/jour
              </span>
            </div>
          </div>
        </div>
      );
    }
    return null;
  };

  return (
    <div className={className}>
      {/* Graphique */}
      <div style={{ width: '100%', height: '240px' }}>
        <ResponsiveContainer width="100%" height="100%">
          <ComposedChart
            data={throughputData}
            margin={{ top: 20, right: 50, left: 20, bottom: 40 }}
          >
            <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
            <XAxis
              dataKey="period"
              stroke="var(--muted-foreground)"
              fontSize={12}
            />
            <YAxis
              yAxisId="points"
              stroke="var(--muted-foreground)"
              fontSize={12}
              label={{ value: 'Points', angle: -90, position: 'insideLeft' }}
            />
            <YAxis
              yAxisId="throughput"
              orientation="right"
              stroke="var(--muted-foreground)"
              fontSize={12}
              label={{
                value: 'Points/jour',
                angle: 90,
                position: 'insideRight',
              }}
            />
            <Tooltip content={<CustomTooltip />} />

            {/* Barres de points complétés */}
            <Bar
              yAxisId="points"
              dataKey="completed"
              fill="hsl(217, 91%, 60%)"
              radius={[4, 4, 0, 0]}
              name="Points complétés"
            />

            {/* Ligne de throughput */}
            <Line
              yAxisId="throughput"
              type="monotone"
              dataKey="throughput"
              stroke="hsl(142, 76%, 36%)"
              strokeWidth={3}
              dot={{ fill: 'hsl(142, 76%, 36%)', strokeWidth: 2, r: 5 }}
              name="Throughput"
            />

            {/* Ligne de tendance (moyenne mobile) */}
            <Line
              yAxisId="throughput"
              type="monotone"
              dataKey="trend"
              stroke="hsl(45, 93%, 47%)"
              strokeWidth={2}
              strokeDasharray="5 5"
              dot={false}
              name="Tendance"
            />
          </ComposedChart>
        </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-3 rounded-sm"
            style={{ backgroundColor: 'var(--blue)' }}
          ></div>
          <span style={{ color: 'var(--blue)' }}>Points complétés</span>
        </div>
        <div className="flex items-center gap-2">
          <div
            className="w-4 h-0.5"
            style={{ backgroundColor: 'var(--green)' }}
          ></div>
          <span style={{ color: 'var(--green)' }}>Throughput</span>
        </div>
        <div className="flex items-center gap-2">
          <div
            className="w-4 h-0.5 border-dashed border-t-2"
            style={{
              backgroundColor: 'var(--accent)',
              borderColor: 'var(--accent)',
            }}
          ></div>
          <span style={{ color: 'var(--accent)' }}>Tendance</span>
        </div>
      </div>

      {/* Métriques de summary */}
      <div className="grid grid-cols-3 gap-4 text-center">
        <div>
          <div className="text-sm font-medium text-green-500">
            {Math.round(avgThroughput * 10) / 10}
          </div>
          <div className="text-xs text-[var(--muted-foreground)]">
            Throughput moyen
          </div>
        </div>
        <div>
          <div className="text-sm font-medium text-blue-500">
            {Math.round(maxThroughput * 10) / 10}
          </div>
          <div className="text-xs text-[var(--muted-foreground)]">
            Pic de throughput
          </div>
        </div>
        <div>
          <div className="text-sm font-medium text-orange-500">
            {throughputData.length > 1
              ? Math.round(
                  (throughputData[throughputData.length - 1].throughput /
                    throughputData[throughputData.length - 2].throughput -
                    1) *
                    100
                )
              : 0}
            %
          </div>
          <div className="text-xs text-[var(--muted-foreground)]">
            Évolution sprint
          </div>
        </div>
      </div>
    </div>
  );
}
