import { data, redirect } from "react-router";
import type { LoaderFunctionArgs } from "react-router";
import { getAuth } from "@clerk/react-router/server";
import {
  findLeagueById,
  findCurrentSeason,
  findTeamsBySeasonId,
  isCommissioner,
  findDraftSlotsBySeasonId,
  getDraftPicks,
  getSeasonTimers,
  findSeasonWithSportsSeasons,
} from "~/models";
import { DraftGrid } from "~/components/draft/DraftGrid";

export async function loader(args: LoaderFunctionArgs) {
  const { userId } = await getAuth(args);
  if (!userId) {
    throw redirect("/");
  }

  const { leagueId } = args.params;
  if (!leagueId) {
    throw new Response("League ID is required", { status: 400 });
  }

  // Get league and season
  const league = await findLeagueById(leagueId);
  if (!league) {
    throw new Response("League not found", { status: 404 });
  }

  const season = await findCurrentSeason(leagueId);
  if (!season) {
    throw new Response("No active season found", { status: 404 });
  }

  // Get season with sports and participants
  const seasonWithSports = await findSeasonWithSportsSeasons(season.id);
  const participants = seasonWithSports?.seasonSports?.flatMap(
    (ss: any) => ss.sportsSeason?.participants || []
  ) || [];

  // Get teams and draft order
  const teams = await findTeamsBySeasonId(season.id);
  const draftSlots = await findDraftSlotsBySeasonId(season.id);
  
  // Sort teams by draft order
  const teamsWithOrder = teams.map((team) => {
    const slot = draftSlots.find((s: { teamId: string }) => s.teamId === team.id);
    return {
      ...team,
      draftOrder: slot?.draftOrder || 0,
    };
  }).sort((a, b) => a.draftOrder - b.draftOrder);

  // Check user permissions
  const isUserCommissioner = await isCommissioner(leagueId, userId);
  const userTeam = teams.find((team) => team.ownerId === userId);

  // Get draft data
  const draftPicks = await getDraftPicks(season.id);
  const timers = await getSeasonTimers(season.id);

  // Calculate current pick info
  const totalPicks = season.draftRounds * teams.length;
  const currentPickNumber = season.currentPickNumber || 1;
  const isDraftComplete = currentPickNumber > totalPicks;

  return data({
    league,
    season,
    teams: teamsWithOrder,
    draftSlots,
    isCommissioner: isUserCommissioner,
    userTeam,
    draftPicks,
    participants,
    timers,
    currentPickNumber,
    totalPicks,
    isDraftComplete,
    userId,
  });
}

export default function DraftRoom({ loaderData }: { loaderData: Awaited<ReturnType<typeof loader>>["data"] }) {
  const {
    league,
    season,
    teams,
    draftPicks,
    participants,
    isCommissioner,
    userTeam,
    currentPickNumber,
    totalPicks,
    isDraftComplete,
  } = loaderData;

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="border-b bg-card">
        <div className="px-6 py-4">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold">{league.name} Draft</h1>
              <p className="text-sm text-muted-foreground">
                {season.year} Season • Pick {currentPickNumber} of {totalPicks}
              </p>
            </div>
            <div className="flex items-center gap-4">
              {isCommissioner && (
                <span className="rounded-full bg-primary/10 px-3 py-1 text-xs font-medium text-primary">
                  Commissioner
                </span>
              )}
              {userTeam && (
                <span className="rounded-full bg-secondary px-3 py-1 text-xs font-medium">
                  {userTeam.name}
                </span>
              )}
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="px-6 py-6">
        {isDraftComplete ? (
          <div className="rounded-lg border bg-card p-8 text-center">
            <h2 className="text-2xl font-bold">Draft Complete!</h2>
            <p className="mt-2 text-muted-foreground">
              All picks have been made. The season is ready to begin.
            </p>
          </div>
        ) : (
          <div className="space-y-6">
            {/* Draft Board - Full Width */}
            <div className="rounded-lg border bg-card p-6">
              <h2 className="mb-4 text-xl font-bold">Draft Board</h2>
              <DraftGrid
                teams={teams}
                draftPicks={draftPicks}
                participants={participants}
                draftRounds={season.draftRounds}
                currentPickNumber={currentPickNumber}
                userTeamId={userTeam?.id}
              />
            </div>

            {/* 2x2 Grid Below */}
            <div className="grid gap-6 md:grid-cols-2">
              {/* Available Players */}
              <div className="rounded-lg border bg-card p-6">
                <h2 className="mb-4 text-xl font-bold">Available Players</h2>
                <div className="flex items-center justify-center py-12 text-muted-foreground">
                  Player list will be implemented in Phase 6
                </div>
              </div>

              {/* Your Queue */}
              <div className="rounded-lg border bg-card p-6">
                <h2 className="mb-4 text-xl font-bold">Your Queue</h2>
                <div className="flex items-center justify-center py-12 text-muted-foreground">
                  Queue will be implemented in Phase 7
                </div>
              </div>

              {/* Draft Timer */}
              <div className="rounded-lg border bg-card p-6">
                <h2 className="mb-4 text-xl font-bold">Draft Timer</h2>
                <div className="flex items-center justify-center py-12 text-muted-foreground">
                  Timer will be implemented in Phase 8
                </div>
              </div>

              {/* Commissioner Controls */}
              {isCommissioner ? (
                <div className="rounded-lg border bg-card p-6">
                  <h2 className="mb-4 text-xl font-bold">Commissioner Controls</h2>
                  <div className="flex items-center justify-center py-12 text-muted-foreground">
                    Controls will be implemented in Phase 9
                  </div>
                </div>
              ) : (
                <div className="rounded-lg border bg-card p-6">
                  <h2 className="mb-4 text-xl font-bold">Draft Info</h2>
                  <div className="space-y-2 text-sm">
                    <div>
                      <span className="text-muted-foreground">Current Pick:</span>
                      <span className="ml-2 font-medium">{currentPickNumber} of {totalPicks}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">Draft Rounds:</span>
                      <span className="ml-2 font-medium">{season.draftRounds}</span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </main>
    </div>
  );
}
