import { prisma } from "@/lib/prisma"
import Navigation from "@/components/Navigation"
import Link from "next/link"
import { notFound } from "next/navigation"
import { ScheduleGenerator } from "@/components/ScheduleGenerator"
import { ScheduleDisplay } from "@/components/ScheduleDisplay"

interface PageProps {
  params: Promise<{
    id: string
  }>
}

// Force dynamic rendering and revalidate on each request
export const dynamic = "force-dynamic"
export const revalidate = 0

export default async function TournamentSchedulePage({ params }: PageProps) {
  const { id } = await params
  const tournamentId = parseInt(id, 10)

  if (isNaN(tournamentId)) {
    notFound()
  }

  console.log(`[Schedule Page] Fetching tournament ${tournamentId}`);
  const tournament = await prisma.event.findUnique({
    where: { id: tournamentId },
    include: {
      participants: {
        include: {
          player: true,
        },
      },
      rounds: {
        orderBy: { roundNumber: "asc" },
        include: {
          bracketMatchups: {
            orderBy: { bracketPosition: "asc" },
            include: {
              player1P1: true,
              player1P2: true,
              player2P1: true,
              player2P2: true,
              match: true,
            },
          },
        },
      },
    },
  })
  console.log(`[Schedule Page] Tournament ${tournamentId} has ${tournament?.rounds?.length || 0} rounds`);
  if (tournament?.rounds && tournament.rounds.length > 0) {
    console.log(`[Schedule Page] First round:`, JSON.stringify(tournament.rounds[0]));
  }

  if (!tournament) {
    notFound()
  }

  const teamCount = tournament.participants.length
  const existingRounds = tournament.rounds.length

  return (
    <div className="min-h-screen bg-gray-50">
      <Navigation />

      <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <div className="px-4 py-6 sm:px-0">
          <div className="mb-6">
            <Link
              href={`/admin/tournaments/${tournamentId}`}
              className="text-green-600 hover:text-green-900"
            >
              ← Back to Tournament
            </Link>
          </div>

          <h1 className="text-3xl font-bold text-gray-900 mb-6">
            Schedule - {tournament.name}
          </h1>

          <div className="bg-white shadow rounded-lg p-6 mb-6">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-xl font-bold text-gray-900">
                Tournament Schedule
              </h2>
            </div>

            <div id="schedule-display">
              {existingRounds > 0 ? (
                <ScheduleDisplay rounds={tournament.rounds} tournamentId={tournamentId} />
              ) : (
                <p className="text-gray-500 mb-6">
                  No schedule has been generated yet. Click "Generate Schedule" to create round matchups.
                </p>
              )}
            </div>

            <div className="mt-6 pt-6 border-t border-gray-200">
              <ScheduleGenerator
                tournamentId={tournamentId}
                teamCount={teamCount}
                existingRounds={existingRounds}
              />
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}
