import { Link } from "react-router";
import { getAuth } from "@clerk/react-router/server";
import { findLeagueById } from "~/models/league";
import { findCurrentSeason } from "~/models/season";
import { findTeamsBySeasonId } from "~/models/team";
import type { Route } from "./+types/$leagueId";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "~/components/ui/card";
import { Button } from "~/components/ui/button";

export async function loader(args: Route.LoaderArgs) {
  const { userId } = await getAuth(args);
  const { params } = args;
  const { leagueId } = params;

  // Fetch league
  const league = await findLeagueById(leagueId);

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

  // Fetch current season
  const season = await findCurrentSeason(leagueId);

  // Fetch teams for current season
  const teams = season ? await findTeamsBySeasonId(season.id) : [];

  return {
    league,
    season,
    teams,
    currentUserId: userId,
  };
}

export default function LeagueHome({ loaderData }: Route.ComponentProps) {
  const { league, season, teams, currentUserId } = loaderData;

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="mb-8">
        <div className="flex items-center justify-between mb-2">
          <h1 className="text-4xl font-bold">{league.name}</h1>
          <Button variant="outline" asChild>
            <Link to="/">Back to Home</Link>
          </Button>
        </div>
        {season && (
          <p className="text-muted-foreground">
            {season.year} Season • Status:{" "}
            <span className="capitalize">
              {season.status.replace("_", " ")}
            </span>
          </p>
        )}
      </div>

      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        <Card className="md:col-span-2 lg:col-span-3">
          <CardHeader>
            <CardTitle>Teams</CardTitle>
            <CardDescription>
              {teams.length} team{teams.length !== 1 ? "s" : ""} in this league
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {teams.map((team) => {
                const isOwned = team.ownerId === currentUserId;
                return (
                  <Card
                    key={team.id}
                    className={isOwned ? "border-primary" : ""}
                  >
                    <CardHeader>
                      <CardTitle className="text-lg">{team.name}</CardTitle>
                      <CardDescription>
                        {team.ownerId ? (
                          isOwned ? (
                            <span className="text-primary font-medium">
                              Your Team
                            </span>
                          ) : (
                            "Owned"
                          )
                        ) : (
                          <span className="text-muted-foreground">
                            Available
                          </span>
                        )}
                      </CardDescription>
                    </CardHeader>
                  </Card>
                );
              })}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>League Info</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            <div>
              <p className="text-sm text-muted-foreground">Created</p>
              <p className="font-medium">
                {new Date(league.createdAt).toLocaleDateString()}
              </p>
            </div>
            {season && (
              <div>
                <p className="text-sm text-muted-foreground">Season Status</p>
                <p className="font-medium capitalize">
                  {season.status.replace("_", " ")}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
