import { BenchmarkResult } from "@/types/benchmark";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { CheckCircle2, XCircle } from "lucide-react";

interface BenchmarkTableProps {
  results: BenchmarkResult[];
}

export const BenchmarkTable = ({ results }: BenchmarkTableProps) => {
  // Sort by average response time (fastest first)
  const sortedResults = [...results].sort((a, b) => {
    if (a.status === "error" && b.status === "success") return 1;
    if (a.status === "success" && b.status === "error") return -1;
    return a.avgResponseTime - b.avgResponseTime;
  });

  // Calculate overall average across all successful attempts
  const allSuccessfulAttempts = sortedResults.flatMap((r) =>
    r.attempts.filter((a) => a.status === "success")
  );
  const overallAvg =
    allSuccessfulAttempts.length > 0
      ? allSuccessfulAttempts.reduce((sum, a) => sum + a.responseTime, 0) /
        allSuccessfulAttempts.length
      : 0;

  return (
    <div className="space-y-4">
      {/* Overall Average */}
      {overallAvg > 0 && (
        <div className="bg-primary/5 border border-primary/20 rounded-lg p-4 flex items-center justify-between">
          <span className="font-semibold text-foreground">
            Overall Average Response Time
          </span>
          <span className="text-2xl font-bold font-mono text-primary">
            {overallAvg.toFixed(0)}ms
          </span>
        </div>
      )}

      {/* Results Table */}
      <div className="rounded-lg border border-border bg-card overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow className="bg-muted/50">
              <TableHead className="font-semibold">URL</TableHead>
              <TableHead className="font-semibold">Implementation</TableHead>
              <TableHead className="font-semibold text-center">Attempt 1</TableHead>
              <TableHead className="font-semibold text-center">Attempt 2</TableHead>
              <TableHead className="font-semibold text-center">Attempt 3</TableHead>
              <TableHead className="font-semibold text-center">Average</TableHead>
              <TableHead className="font-semibold">Status</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedResults.map((result, index) => (
              <TableRow key={index} className="hover:bg-muted/30 transition-colors">
                <TableCell className="font-mono text-sm text-muted-foreground">
                  {result.mirrorUrl}
                </TableCell>
                <TableCell className="font-medium">
                  {result.implementation}
                </TableCell>
                {result.attempts.map((attempt, attemptIndex) => (
                  <TableCell key={attemptIndex} className="text-center font-mono text-sm">
                    {attempt.status === "success" ? (
                      <span className="text-foreground">
                        {attempt.responseTime.toFixed(0)}ms
                      </span>
                    ) : (
                      <span className="text-destructive">
                        <XCircle className="w-4 h-4 inline" />
                      </span>
                    )}
                  </TableCell>
                ))}
                <TableCell className="text-center font-mono text-sm">
                  {result.status === "success" ? (
                    <span className="font-bold text-primary text-base">
                      {result.avgResponseTime.toFixed(0)}ms
                    </span>
                  ) : (
                    <span className="text-muted-foreground">—</span>
                  )}
                </TableCell>
                <TableCell>
                  {result.status === "success" ? (
                    <Badge
                      variant="outline"
                      className="bg-success/10 text-success border-success/20 gap-1"
                    >
                      <CheckCircle2 className="w-3 h-3" />
                      Success
                    </Badge>
                  ) : (
                    <Badge
                      variant="outline"
                      className="bg-destructive/10 text-destructive border-destructive/20 gap-1"
                    >
                      <XCircle className="w-3 h-3" />
                      Error
                    </Badge>
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        {sortedResults.length === 0 && (
          <div className="text-center py-12 text-muted-foreground">
            No results yet. Enter a DID and run the benchmark.
          </div>
        )}
      </div>
    </div>
  );
};
