import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import type { GitCommit, HeatmapDay } from "@/lib/git-analyzer";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

function getDaysAgo(date: Date): number {
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  return Math.floor(diff / (1000 * 60 * 60 * 24));
}

interface CommitHistoryProps {
  commits: GitCommit[];
  days?: number;
  startDate?: Date;
}

export function CommitHistory({ commits, days = 365 }: CommitHistoryProps) {
  const authorMap = new Map<string, { count: number; percentage: number }>();
  for (const c of commits) {
    if (!authorMap.has(c.author)) {
      authorMap.set(c.author, { count: 0, percentage: 0 });
    }
    authorMap.get(c.author)!.count += 1;
  }
  for (const [author, data] of authorMap) {
    data.percentage = commits.length > 0 ? Math.round((data.count / commits.length) * 100) : 0;
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Fréquence par contributeur</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {Array.from(authorMap.entries()).map(([author, data]) => (
            <div key={author} className="space-y-1">
              <div className="flex justify-between text-sm">
                <span className="font-medium">{author}</span>
                <span className="text-muted-foreground">{data.percentage}%</span>
              </div>
              <Progress value={data.percentage} />
            </div>
          ))}
          {commits.length === 0 && (
            <p className="text-sm text-muted-foreground">Aucune donnée</p>
          )}
        </div>
      </CardContent>
    </Card>
  );
}

function getHeatmapColor(level: number): string {
  const colors = ["#ebedf0", "#c6e48e", "#7bc96f", "#239a3b", "#196127", "#006031"];
  return colors[level] || colors[0];
}

export function ContributionHeatmap({ heatmap, days = 365 }: { heatmap: HeatmapDay[]; days?: number }) {
  const weeks = Math.ceil(days / 7);

  // Create heatmap grid
  const heatmapGrid: { date: string; day: number; count: number; color: string }[][] = [];
  
  for (let week = 0; week < weeks; week++) {
    const weekData: { date: string; day: number; count: number; color: string }[] = [];
    for (let day = 0; day < 7; day++) {
      const date = new Date(Date.now() - (week * 7 + day) * 24 * 60 * 60 * 1000);
      const dateStr = date.toISOString().split("T")[0];
      const found = heatmap.find(h => h.date === dateStr);
      const count = found?.count || 0;
      const color = getHeatmapColor(count);
      
      weekData.push({
        date: dateStr,
        day: date.getDay(),
        count,
        color,
      });
    }
    heatmapGrid.push(weekData);
  }

  const dayLabels = ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"];

  return (
    <Card>
      <CardHeader>
        <CardTitle>Intensité des contributions</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          <div className="flex items-center justify-center gap-1">
            {heatmapGrid[heatmapGrid.length - 1]?.map((row, wIdx) => (
              <div key={wIdx} className="w-3 h-3 rounded-sm" style={{ backgroundColor: row.color }} />
            ))}
            <span className="text-xs text-muted-foreground ml-2">{days} jours</span>
          </div>
          
          <div className="grid grid-cols-7 gap-1">
            {dayLabels.map((label, idx) => (
              <div key={label} className="text-xs text-center text-muted-foreground">
                {label}
              </div>
            ))}
            {heatmapGrid.map((week, wIdx) =>
              week.map((cell, dIdx) => (
                <div
                  key={wIdx}
                  style={{ 
                    backgroundColor: cell.color,
                    width: 12,
                    height: 12,
                    borderRadius: 2,
                  }}
                  title={`${cell.date}: ${cell.count} commits`}
                  className="transition-transform hover:scale-125 cursor-help"
                />
              ))
            )}
          </div>
          
          <div className="flex items-center justify-end gap-2 text-xs text-muted-foreground">
            <span>Moins</span>
            <div className="w-3 h-3 rounded-sm" style={{ backgroundColor: "#ebedf0" }} />
            <div className="w-3 h-3 rounded-sm" style={{ backgroundColor: "#c6e48e" }} />
            <div className="w-3 h-3 rounded-sm" style={{ backgroundColor: "#7bc96f" }} />
            <div className="w-3 h-3 rounded-sm" style={{ backgroundColor: "#239a3b" }} />
            <div className="w-3 h-3 rounded-sm" style={{ backgroundColor: "#006031" }} />
            <span>Plus</span>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

function CommitTypeBreakdown({ commitTypes }: { commitTypes: Array<{ type: string; percentage: number }> }) {
  const typeColors: Record<string, string> = {
    feat: "bg-emerald-500",
    fix: "bg-orange-500",
    refactor: "bg-purple-500",
    docs: "bg-blue-500",
    style: "bg-pink-500",
    chore: "bg-gray-500",
    perf: "bg-red-500",
    test: "bg-yellow-500",
    ci: "bg-indigo-500",
    build: "bg-cyan-500",
    revert: "bg-slate-500",
  };

  const typeLabels: Record<string, string> = {
    feat: 'Nouveau',
    fix: 'Correction',
    refactor: 'Refactorisation',
    docs: 'Documentation',
    style: 'Style',
    chore: 'Tâche',
    perf: 'Performance',
    test: 'Test',
    ci: 'CI/CD',
    build: 'Build',
    revert: 'Annulation',
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Répartition des commits</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          {commitTypes.map(({ type, percentage }) => (
            <div key={type} className="flex items-center gap-3">
              <div
                className={`w-4 h-4 rounded-sm ${typeColors[type] || 'bg-gray-400'}`}
              />
              <div className="flex-1">
                <div className="flex justify-between text-sm">
                  <span>{typeLabels[type] || type}</span>
                  <span className="font-medium">{percentage}%</span>
                </div>
                <div className="w-full bg-muted rounded-full h-2 mt-1">
                  <div
                    className={`h-2 rounded-full ${typeColors[type] || 'bg-gray-400'}`}
                    style={{ width: `${percentage}%` }}
                  />
                </div>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

function ContributionBreakdown({ contributors }: { contributors: any[] }) {
  return (
    <Card>
      <CardHeader>
        <CardTitle>Répartition des contributions</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          <div className="flex items-center justify-center p-4">
            <div className="relative w-32 h-32">
              <svg viewBox="0 0 32 32" className="w-full h-full transform -rotate-90">
                <circle
                  cx="16"
                  cy="16"
                  r="14"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="4"
                  className="text-muted/10"
                />
                {contributors.map((_, idx) => {
                  const colors = ["#0ea5e9", "#f97316", "#8b5cf6", "#10b981", "#6366f1"];
                  const total = contributors.reduce((sum, c) => sum + c.commits, 0);
                  const count = contributors[idx]?.commits || 0;
                  const percentage = (count / total) * 100;
                  const dashArray = `${percentage * 0.88} ${100 - percentage * 0.88}`;
                  const dashOffset = total
                    ? -contributors.slice(0, idx).reduce((sum, c) => sum + (c.commits / total) * 88, 0)
                    : 0;
                  
                  return (
                    <circle
                      key={idx}
                      cx="16"
                      cy="16"
                      r="14"
                      fill="none"
                      stroke={colors[idx % colors.length]}
                      strokeWidth="4"
                      strokeDasharray={dashArray}
                      strokeDashoffset={dashOffset}
                    />
                  );
                })}
              </svg>
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="text-center">
                  <p className="text-xs text-muted-foreground">Total</p>
                  <p className="text-lg font-bold">{contributors.reduce((sum, c) => sum + c.commits, 0)}</p>
                </div>
              </div>
            </div>
          </div>
          
          <div className="space-y-3">
            {contributors.map((contributor, idx) => {
              const total = contributors.reduce((sum, c) => sum + c.commits, 0);
              const percentage = total ? Math.round((contributor.commits / total) * 100) : 0;
              const colors = ["#0ea5e9", "#f97316", "#8b5cf6", "#10b981", "#6366f1"];
              
              return (
                <div key={idx} className="flex items-center gap-3">
                  <div
                    className="w-3 h-3 rounded-full"
                    style={{ backgroundColor: colors[idx % colors.length] }}
                  />
                  <div className="flex-1">
                    <div className="flex justify-between text-sm">
                      <span className="font-medium">{contributor.name}</span>
                      <span className="text-muted-foreground">{percentage}%</span>
                    </div>
                    <div className="w-full bg-muted rounded-full h-2 mt-1">
                      <div
                        className="h-2 rounded-full"
                        style={{ 
                          width: `${percentage}%`,
                          backgroundColor: colors[idx % colors.length]
                        }}
                      />
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

function CommitTimeline({ dailyCommits }: { dailyCommits: { date: string; count: number }[] }) {
  const maxCount = Math.max(...dailyCommits.map(c => c.count), 1);
  const today = new Date();
  const startDate = new Date(today);
  startDate.setDate(startDate.getDate() - 365);

  const data = dailyCommits.filter(c => {
    const date = new Date(c.date);
    return date >= startDate && date <= today;
  });

  return (
    <Card>
      <CardHeader>
        <CardTitle>Historique des commits</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          <div className="flex items-end gap-0.5 h-32">
            {data.map((point, idx) => {
              const height = Math.max((point.count / maxCount) * 100, 5);
              const date = new Date(point.date);
              const isWeekend = [0, 6].includes(date.getDay());
              
              return (
                <div
                  key={idx}
                  className="flex-1 flex flex-col items-center gap-1"
                  title={`${point.date}: ${point.count} commits`}
                >
                  <div
                    className={`w-full min-w-[2px] rounded-t ${
                      isWeekend ? 'bg-blue-400' : 'bg-blue-500'
                    }`}
                    style={{ height: `${height}%` }}
                  />
                  {idx % 30 === 0 && (
                    <span className="text-xs text-muted-foreground">
                      {date.toLocaleDateString('fr-FR', { month: 'short' })}
                    </span>
                  )}
                </div>
              );
            })}
          </div>
          
          <div className="flex justify-between text-xs text-muted-foreground">
            <span>{startDate.toLocaleDateString('fr-FR', { month: 'short', day: 'numeric' })}</span>
            <span>Aujourd'hui</span>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

function MostActivePeriod({ mostActive, allTime, lastWeek }: { mostActive: Array<{ type: string; count: number }>; allTime: Array<{ type: string; count: number }>; lastWeek: Array<{ type: string; count: number }> }) {
  const getMostActive = (period: Array<{ type: string; count: number }>) => {
    const max = Math.max(...period.map(p => p.count));
    return period.find(p => p.count === max);
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>Périodes les plus actives</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-3 gap-4">
          {[
            { period: 'Aujourd\'hui', data: mostActive },
            { period: 'Cette semaine', data: lastWeek },
            { period: 'Total', data: allTime },
          ].map(({ period, data }) => {
            const most = getMostActive(data);
            return (
              <div key={period} className="p-3 bg-muted/50 rounded-md">
                <p className="text-sm font-medium">{period}</p>
                <p className="text-2xl font-bold mt-1">{most?.count || 0}</p>
                <p className="text-xs text-muted-foreground">{most?.type || '-'}</p>
              </div>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}
