import { useLoaderData } from "react-router";
import type { Route } from "./+types/$leagueId.standings.$seasonId.teams.$teamId";

import { TeamScoreBreakdown } from "~/components/standings/TeamScoreBreakdown";
import { getTeamScoreBreakdown, getTeamStanding } from "~/models/standings";
import { getNumTeamsInSeason } from "~/models/draft-slot";

export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
  return [{ title: `${data?.breakdown?.team?.name ?? "Team"} - Brackt` }];
}

/**
 * Team score breakdown page
 * Shows all drafted participants with their placements and points
 * Phase 4.3: Team breakdown pages
 */
export async function loader({ params }: Route.LoaderArgs) {
  const { leagueId, seasonId, teamId } = params;

  // Get team breakdown with all picks
  const [breakdown, standing, numTeams] = await Promise.all([
    getTeamScoreBreakdown(teamId, seasonId),
    getTeamStanding(teamId, seasonId),
    getNumTeamsInSeason(seasonId),
  ]);

  if (!breakdown) {
    throw new Response("Team not found", { status: 404 });
  }

  return {
    leagueId,
    seasonId,
    teamId,
    breakdown: {
      ...breakdown,
      team: breakdown.team || null,
    },
    standing,
    numTeams,
  };
}

export default function TeamBreakdownPage() {
  const { leagueId, seasonId, breakdown, standing, numTeams } = useLoaderData<typeof loader>();

  return (
    <div className="container mx-auto py-8 px-4">
      <TeamScoreBreakdown
        leagueId={leagueId}
        seasonId={seasonId}
        breakdown={breakdown}
        standing={standing}
        numTeams={numTeams}
      />
    </div>
  );
}
