import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";

interface DailyData {
  date: string;
  count: number;
}

interface ActiveDaysProps {
  title?: string;
  dailyCommits: DailyData[];
  className?: string;
}

export function ActiveDaysChart({ title, dailyCommits, className }: ActiveDaysProps) {
  const sortedData = [...dailyCommits]
    .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
    .slice(-30);

  const chartData = sortedData.map((d) => {
    const date = new Date(d.date);
    const label = `${date.getDate()}/${date.getMonth() + 1}`;
    // Calculate 7-day moving average
    const idx = sortedData.indexOf(d);
    let avg = 0;
    if (idx >= 6) {
      const slice = sortedData.slice(idx - 6, idx + 1);
      avg = parseFloat(
        (slice.reduce((sum, c) => sum + c.count, 0) / 6).toFixed(1)
      );
    }
    return { ...d, label, average: idx >= 6 ? avg : 0 };
  });

  return (
    <div className={className}>
      <h4 className="text-sm font-semibold mb-4">{title || "Activité des jours"}</h4>
      <div className="h-64">
        <ResponsiveContainer width="100%" height="100%">
          <LineChart data={chartData}>
            <CartesianGrid strokeDasharray="3 3" stroke="rgba(0,0,0,0.05)" />
            <XAxis
              dataKey="label"
              tick={{ fontSize: 10 }}
              stroke="rgba(0,0,0,0.1)"
            />
            <YAxis
              tick={{ fontSize: 10 }}
              stroke="rgba(0,0,0,0.1)"
              allowDecimals={false}
            />
            <Tooltip
              contentStyle={{
                backgroundColor: "rgba(0,0,0,0.8)",
                color: "#fff",
                borderRadius: 6,
                fontSize: 11,
              }}
              formatter={(value: number, name: string) => [
                `${value} commits`,
                name === "average" ? "Moyenne mobile (7j)" : "Commits",
              ]}
            />
            <Line
              type="monotone"
              dataKey="count"
              stroke="#3b82f6"
              strokeWidth={2}
              dot={false}
              activeDot={{ r: 4 }}
              fill="rgba(59, 130, 246, 0.1)"
            />
            <Line
              type="monotone"
              dataKey="average"
              stroke="#10b981"
              strokeWidth={2}
              strokeDasharray="5 5"
              dot={false}
            />
          </LineChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
