import { Link } from "react-router";
import { Card, CardHeader, CardTitle, CardContent, CardDescription } from "~/components/ui/card";
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "~/components/ui/table";
import { Badge } from "~/components/ui/badge";
import { Button } from "~/components/ui/button";

interface TeamScoreBreakdownProps {
  leagueId: string;
  seasonId: string;
  breakdown: {
    team: {
      id: string;
      name: string;
    } | null;
    picks: Array<{
      pickNumber: number;
      round: number;
      participant: {
        id: string;
        name: string;
        sport: string;
        sportsSeasonId: string;
      };
      finalPosition: number | null;
      points: number;
      projectedPoints: number | null;
      isComplete: boolean;
    }>;
    bySport: Record<string, { sportsSeasonId: string; picks: Array<{
      pickNumber: number;
      round: number;
      participant: {
        id: string;
        name: string;
        sport: string;
        sportsSeasonId: string;
      };
      finalPosition: number | null;
      points: number;
      projectedPoints: number | null;
      isComplete: boolean;
    }> }>;
    totalPoints: number;
    actualPoints: number;
    projectedPoints: number;
    completedCount: number;
    totalCount: number;
  };
  standing: {
    currentRank: number;
    placementCounts: {
      first: number;
      second: number;
      third: number;
      fourth: number;
      fifth: number;
      sixth: number;
      seventh: number;
      eighth: number;
    };
  } | null;
}

/**
 * Display detailed team score breakdown with all drafted participants
 * Phase 4.3: Team breakdown pages
 */
export function TeamScoreBreakdown({
  leagueId,
  seasonId,
  breakdown,
  standing,
}: TeamScoreBreakdownProps) {
  if (!breakdown.team) {
    return (
      <div className="text-center text-muted-foreground py-8">
        Team not found
      </div>
    );
  }

  const sportEntries = Object.entries(breakdown.bySport).sort(([a], [b]) => a.localeCompare(b));

  return (
    <div className="space-y-6">
      {/* Header with team info and summary */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-3xl font-bold">{breakdown.team.name}</h1>
          <p className="text-muted-foreground mt-1">
            Team Score Breakdown
          </p>
        </div>
        <div className="text-right">
          <div className="text-4xl font-bold text-primary">
            {breakdown.actualPoints.toFixed(2)}
          </div>
          <div className="text-sm text-muted-foreground">
            Actual Points
          </div>
          {breakdown.projectedPoints > breakdown.actualPoints && (
            <div className="text-xl font-semibold text-electric mt-1">
              {breakdown.projectedPoints.toFixed(2)}
              <span className="text-xs text-muted-foreground ml-1">projected</span>
            </div>
          )}
          {standing && (
            <Badge className="mt-2" variant={standing.currentRank <= 3 ? "default" : "outline"}>
              Rank #{standing.currentRank}
            </Badge>
          )}
        </div>
      </div>

      {/* Summary stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Actual Points
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {breakdown.actualPoints.toFixed(2)}
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              From {breakdown.completedCount} finished
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Projected Points
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-primary">
              {breakdown.projectedPoints.toFixed(2)}
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              +{(breakdown.projectedPoints - breakdown.actualPoints).toFixed(2)} expected value
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Participants
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {breakdown.completedCount} / {breakdown.totalCount}
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              {breakdown.totalCount - breakdown.completedCount} remaining
            </p>
          </CardContent>
        </Card>

        {standing && (
          <>
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  Top Finishes
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-1">
                  {standing.placementCounts.first > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-amber-accent font-medium">1st place</span>
                      <span className="font-bold">{standing.placementCounts.first}</span>
                    </div>
                  )}
                  {standing.placementCounts.second > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground font-medium">2nd place</span>
                      <span className="font-bold">{standing.placementCounts.second}</span>
                    </div>
                  )}
                  {standing.placementCounts.third > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-coral-accent font-medium">3rd place</span>
                      <span className="font-bold">{standing.placementCounts.third}</span>
                    </div>
                  )}
                  {standing.placementCounts.first === 0 &&
                   standing.placementCounts.second === 0 &&
                   standing.placementCounts.third === 0 && (
                    <p className="text-sm text-muted-foreground">No podium finishes yet</p>
                  )}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-sm font-medium text-muted-foreground">
                  All Placements
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-x-3 gap-y-1 text-xs">
                  {[
                    { label: "4th", count: standing.placementCounts.fourth },
                    { label: "5th", count: standing.placementCounts.fifth },
                    { label: "6th", count: standing.placementCounts.sixth },
                    { label: "7th", count: standing.placementCounts.seventh },
                    { label: "8th", count: standing.placementCounts.eighth },
                  ].map((item) => (
                    <div key={item.label} className="flex justify-between">
                      <span className="text-muted-foreground">{item.label}:</span>
                      <span className="font-medium">{item.count}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </>
        )}
      </div>

      {/* Participants grouped by sport */}
      {sportEntries.map(([sportName, sportData]) => {
        const { sportsSeasonId, picks: sportPicks } = sportData;
        const sportTotal = sportPicks.reduce((sum: number, p) => sum + p.points, 0);
        const sportCompleted = sportPicks.filter((p) => p.isComplete).length;

        return (
          <Card key={sportName}>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <div className="flex items-center gap-2">
                    <CardTitle>{sportName}</CardTitle>
                    <Button asChild variant="ghost" size="sm" className="h-6 px-2 text-xs">
                      <Link to={`/leagues/${leagueId}/sports-seasons/${sportsSeasonId}`}>
                        View Details →
                      </Link>
                    </Button>
                  </div>
                  <CardDescription>
                    {sportPicks.length} {sportPicks.length === 1 ? 'pick' : 'picks'} · {sportCompleted} completed
                  </CardDescription>
                </div>
                <div className="text-right">
                  <div className="text-2xl font-bold">{sportTotal.toFixed(2)}</div>
                  <div className="text-xs text-muted-foreground">points</div>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[100px]">Pick #</TableHead>
                    <TableHead>Participant</TableHead>
                    <TableHead className="text-center">Position</TableHead>
                    <TableHead className="text-right">Points</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {sportPicks.map((pick: typeof sportPicks[number]) => (
                    <TableRow key={pick.pickNumber}>
                      <TableCell className="text-muted-foreground">
                        #{pick.pickNumber}
                        <span className="text-xs ml-1">(R{pick.round})</span>
                      </TableCell>
                      <TableCell className="font-medium">
                        {pick.participant.name}
                      </TableCell>
                      <TableCell className="text-center">
                        {pick.isComplete ? (
                          pick.finalPosition === 0 ? (
                            <Badge variant="secondary">
                              Did Not Score
                            </Badge>
                          ) : (
                            <PlacementBadge position={pick.finalPosition!} />
                          )
                        ) : (
                          <Badge variant="outline">Pending</Badge>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        {pick.isComplete ? (
                          <span className="font-semibold">
                            {pick.points > 0 ? pick.points.toFixed(2) : '0.0'}
                          </span>
                        ) : pick.projectedPoints !== null ? (
                          <div className="flex flex-col items-end">
                            <span className="text-xs text-muted-foreground">Projected:</span>
                            <span className="font-semibold text-primary">
                              {pick.projectedPoints.toFixed(2)}
                            </span>
                          </div>
                        ) : (
                          <span className="text-muted-foreground">-</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        );
      })}

      {/* Navigation */}
      <div className="flex justify-between pt-4">
        <Button asChild variant="outline">
          <Link to={`/leagues/${leagueId}/standings/${seasonId}`}>
            ← Back to Standings
          </Link>
        </Button>
      </div>
    </div>
  );
}

/**
 * Display placement badge with color coding
 */
function PlacementBadge({ position }: { position: number }) {
  const badges: Record<number, { label: string; className: string }> = {
    1: { label: "1st", className: "bg-amber-accent hover:bg-amber-accent/80 text-background" },
    2: { label: "2nd", className: "bg-muted hover:bg-muted/80 text-muted-foreground" },
    3: { label: "3rd", className: "bg-coral-accent hover:bg-coral-accent/80 text-background" },
    4: { label: "4th", className: "bg-electric/20 hover:bg-electric/30 text-electric" },
    5: { label: "5th", className: "bg-purple-500/20 hover:bg-purple-500/30 text-purple-400" },
    6: { label: "6th", className: "bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400" },
    7: { label: "7th", className: "bg-pink-500/20 hover:bg-pink-500/30 text-pink-400" },
    8: { label: "8th", className: "bg-indigo-500/20 hover:bg-indigo-500/30 text-indigo-400" },
  };

  const badge = badges[position] || { label: `${position}th`, className: "" };

  return (
    <Badge className={badge.className}>
      {badge.label}
    </Badge>
  );
}
