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, canDeleteTournament } from "@/lib/permissions"
import { getTournamentStatus } from "@/lib/tournamentUtils"
import { DeleteTournamentButton } from "@/components/DeleteTournamentButton"

interface PageProps {
  params: {
    id: string
  }
}

export default async function TournamentDetailPage({ 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")
  }

  // Check if user can delete this tournament
  const deletePermission = await canDeleteTournament(tournamentId)

  let tournament = await prisma.event.findUnique({
    where: { id: tournamentId },
    include: {
      participants: {
        include: {
          player: true,
        },
      },
      teams: {
        include: {
          player1: true,
          player2: true,
        },
      },
      rounds: {
        include: {
          bracketMatchups: {
            include: {
              team1: {
                include: {
                  player1: true,
                  player2: true,
                },
              },
              team2: {
                include: {
                  player1: true,
                  player2: true,
                },
              },
              match: true,
            },
          },
        },
      },
    },
  })

  if (!tournament) {
    notFound()
  }

  // Update tournament status based on event date
  const calculatedStatus = getTournamentStatus(tournament.eventDate);
  if (tournament.status !== calculatedStatus) {
    tournament = await prisma.event.update({
      where: { id: tournamentId },
      data: { status: calculatedStatus },
      include: {
        participants: {
          include: {
            player: true,
          },
        },
        teams: {
          include: {
            player1: true,
            player2: true,
          },
        },
        rounds: {
          include: {
            bracketMatchups: {
              include: {
                team1: {
                  include: {
                    player1: true,
                    player2: true,
                  },
                },
                team2: {
                  include: {
                    player1: true,
                    player2: true,
                  },
                },
                match: true,
              },
            },
          },
        },
      },
    });
  }

  const matches = await prisma.match.findMany({
    where: { eventId: tournamentId },
    include: {
      team1P1: true,
      team1P2: true,
      team2P1: true,
      team2P2: true,
    },
    orderBy: { playedAt: "desc" },
  })

  const matchCount = matches.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">
          {/* 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 className="text-gray-600">{tournament.name}</li>
            </ol>
          </nav>

          {/* Tournament Header */}
          <div className="bg-white shadow rounded-lg p-6 mb-6">
            <div className="flex justify-between items-start">
              <div>
                <h1 className="text-2xl font-bold text-gray-900">{tournament.name}</h1>
                <p className="text-gray-500 mt-1">
                  {tournament.format} - {tournament.status}
                </p>
                {tournament.eventDate && (
                  <p className="text-sm text-gray-400 mt-1">
                    {new Date(tournament.eventDate).toLocaleDateString()}
                  </p>
                )}
              </div>
              <div className="flex space-x-2">
                {permission.allowed && (
                  <>
                    <Link
                      href={`/admin/tournaments/${tournament.id}/edit`}
                      className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
                    >
                      Edit
                    </Link>
                    <Link
                      href={`/admin/tournaments/${tournament.id}/results`}
                      className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700"
                    >
                      Enter Results
                    </Link>
                    <a
                      href={`/api/tournaments/${tournament.id}/export`}
                      className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
                    >
                      Export CSV
                    </a>
                    {deletePermission.allowed && (
                      <DeleteTournamentButton
                        tournamentId={tournament.id}
                        tournamentName={tournament.name}
                        matchCount={matchCount}
                      />
                    )}
                  </>
                )}
              </div>
            </div>

            {/* Quick Stats */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
              <div className="bg-gray-50 rounded-lg p-4 text-center">
                <p className="text-sm text-gray-500">Participants</p>
                <p className="text-2xl font-bold text-gray-900">
                  {tournament.participants.length}
                </p>
              </div>
              <div className="bg-gray-50 rounded-lg p-4 text-center">
                <p className="text-sm text-gray-500">Teams</p>
                <p className="text-2xl font-bold text-gray-900">
                  {tournament.teams.length}
                </p>
              </div>
              <div className="bg-gray-50 rounded-lg p-4 text-center">
                <p className="text-sm text-gray-500">Rounds</p>
                <p className="text-2xl font-bold text-gray-900">
                  {tournament.rounds.length}
                </p>
              </div>
              <div className="bg-gray-50 rounded-lg p-4 text-center">
                <p className="text-sm text-gray-500">Matches</p>
                <p className="text-2xl font-bold text-gray-900">
                  {matches.length}
                </p>
              </div>
            </div>
          </div>

          {/* Tabs */}
          <div className="border-b border-gray-200">
            <nav className="-mb-px flex space-x-8">
              <button className="border-green-500 text-green-600 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                Overview
              </button>
              <button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                Participants
              </button>
              <button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                Teams
              </button>
              <button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                Schedule
              </button>
              <button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                Results
              </button>
              <button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                Analytics
              </button>
            </nav>
          </div>

          {/* Content */}
          <div className="mt-6">
            {/* Participants Section */}
            <div className="bg-white shadow rounded-lg p-6 mb-6">
              <h2 className="text-lg font-medium text-gray-900 mb-4">
                Participants ({tournament.participants.length})
              </h2>
              
              {tournament.participants.length > 0 ? (
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  {tournament.participants.map((participant) => (
                    <div
                      key={participant.id}
                      className="bg-gray-50 rounded p-2 text-center"
                    >
                      <Link
                        href={`/players/${participant.player.id}/profile`}
                        className="text-green-600 hover:text-green-900 text-sm"
                      >
                        {participant.player.name}
                      </Link>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-500">No participants registered yet.</p>
              )}
            </div>

            {/* Teams Section */}
            <div className="bg-white shadow rounded-lg p-6 mb-6">
              <h2 className="text-lg font-medium text-gray-900 mb-4">
                Teams ({tournament.teams.length})
              </h2>
              
              {tournament.teams.length > 0 ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {tournament.teams.map((team) => (
                    <div
                      key={team.id}
                      className="bg-gray-50 rounded p-3 flex justify-between items-center"
                    >
                      <div>
                        <p className="font-medium text-gray-900">
                          {team.player1.name} + {team.player2.name}
                        </p>
                        <p className="text-sm text-gray-500">{team.teamName}</p>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-500">No teams created yet.</p>
              )}
            </div>

            {/* Recent Matches Section */}
            <div className="bg-white shadow rounded-lg p-6">
              <h2 className="text-lg font-medium text-gray-900 mb-4">
                Recent Matches ({matches.length})
              </h2>
              
              {matches.length > 0 ? (
                <div className="space-y-3">
                  {matches.slice(0, 10).map((match) => (
                    <div
                      key={match.id}
                      className="border border-gray-200 rounded p-3"
                    >
                      <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.team1P1.name} + {match.team1P2.name} vs{" "}
                            {match.team2P1.name} + {match.team2P2.name}
                          </p>
                        </div>
                        <div className="text-right">
                          <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>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-500">No matches recorded yet.</p>
              )}
            </div>
          </div>
        </div>
      </main>
    </div>
  )
}
