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,
} from "~/models";

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 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,
    timers,
    currentPickNumber,
    totalPicks,
    isDraftComplete,
    userId,
  });
}

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

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <header className="border-b bg-card">
        <div className="container mx-auto px-4 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="container mx-auto px-4 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="grid gap-6 lg:grid-cols-[1fr_400px]">
            {/* Left Column - Draft Grid & Player List */}
            <div className="space-y-6">
              {/* Draft Grid Placeholder */}
              <div className="rounded-lg border bg-card p-6">
                <h2 className="mb-4 text-xl font-bold">Draft Board</h2>
                <div className="flex items-center justify-center py-12 text-muted-foreground">
                  Draft grid will be implemented in Phase 5
                </div>
              </div>

              {/* Player List Placeholder */}
              <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>
            </div>

            {/* Right Column - Queue & Controls */}
            <div className="space-y-6">
              {/* Queue Placeholder */}
              <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>

              {/* Timer Placeholder */}
              <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>
          </div>
        )}
      </main>
    </div>
  );
}
