import { prisma } from "@/lib/prisma"
export const dynamic = "force-dynamic";
import Navigation from "@/components/Navigation"
import Link from "next/link"
import { notFound, redirect } from "next/navigation"
import { canManageTournament } from "@/lib/permissions"
import MatchEditor from "@/components/MatchEditor"

interface PageProps {
  params: {
    id: string
  }
}

export default async function TournamentResultsPage({ params }: PageProps) {
  // Next.js 16 requires awaiting params
  const { id } = await params
  const tournamentId = parseInt(id, 10)
  
  if (isNaN(tournamentId)) {
    notFound()
  }
  
  // Check if user can manage this tournament
  const permission = await canManageTournament(tournamentId)
  if (!permission.allowed) {
    redirect("/auth/login")
  }

  const tournament = await prisma.event.findUnique({
    where: { id: tournamentId },
  })

  if (!tournament) {
    notFound()
  }

  const matches = await prisma.match.findMany({
    where: { eventId: tournamentId },
    include: {
      player1P1: true,
      player1P2: true,
      player2P1: true,
      player2P2: true,
    },
    orderBy: { playedAt: "desc" },
  })

  const players = await prisma.player.findMany({
    orderBy: { name: "asc" },
  })

  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">
          {/* Breadcrumb */}
          <nav className="mb-4">
            <ol className="flex items-center space-x-2">
              <li>
                <Link href="/admin/tournaments" className="text-green-600 hover:text-green-900">
                  Tournaments
                </Link>
              </li>
              <li className="text-gray-400">/</li>
              <li>
                <Link href={`/admin/tournaments/${tournament.id}`} className="text-green-600 hover:text-green-900">
                  {tournament.name}
                </Link>
              </li>
              <li className="text-gray-400">/</li>
              <li className="text-gray-600">Enter Results</li>
            </ol>
          </nav>

          {/* Page Header */}
          <div className="bg-white shadow rounded-lg p-6 mb-6">
            <h1 className="text-2xl font-bold text-gray-900">Enter Match Results</h1>
            <p className="text-gray-500 mt-1">
              Record match results for {tournament.name}.
            </p>
          </div>

          {/* Match Editor */}
          <div className="bg-white shadow rounded-lg p-6">
            <MatchEditor 
              tournamentId={tournamentId} 
              players={players} 
              matches={matches}
              targetScore={tournament.targetScore}
              allowTies={tournament.allowTies}
            />
          </div>

          {/* Existing Matches */}
          {matches.length > 0 && (
            <div className="bg-white shadow rounded-lg p-6 mt-6">
              <h2 className="text-lg font-medium text-gray-900 mb-4">
                Recent Matches
              </h2>
              
              <div className="space-y-3">
                {matches.slice(0, 10).map((match) => (
                  <Link
                    key={match.id}
                    href={`/matches/${match.id}`}
                    className="block border border-gray-200 rounded p-3 hover:border-green-300 hover:bg-green-50 transition-colors"
                  >
                    <div className="flex justify-between items-center">
                      <div className="flex-1">
                        <p className="text-sm text-gray-500">
                          {match.playedAt?.toLocaleDateString()}
                        </p>
                        <p className="font-medium">
                          {match.player1P1?.name} + {match.player1P2?.name} vs{" "}
                          {match.player2P1?.name} + {match.player2P2?.name}
                        </p>
                      </div>
                      <div className="text-right flex items-center">
                        <span className={`font-bold ${
                          match.team1Score > match.team2Score
                            ? 'text-green-600'
                            : match.team1Score < match.team2Score
                            ? 'text-red-600'
                            : 'text-gray-600'
                        }`}>
                          {match.team1Score}
                        </span>
                        <span className="text-gray-400 mx-2">-</span>
                        <span className={`font-bold ${
                          match.team2Score > match.team1Score
                            ? 'text-green-600'
                            : match.team2Score < match.team1Score
                            ? 'text-red-600'
                            : 'text-gray-600'
                        }`}>
                          {match.team2Score}
                        </span>
                        <svg
                          className="ml-3 h-5 w-5 text-gray-400"
                          fill="none"
                          stroke="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={2}
                            d="M9 5l7 7-7 7"
                          />
                        </svg>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          )}
        </div>
      </main>
    </div>
  )
}
