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

interface PageProps {
  params: {
    id: string
  }
}

export default async function PlayerSchedulePage({ params }: PageProps) {
  // Next.js 16 requires awaiting params
  const { id } = await params
  const playerId = parseInt(id, 10)
  
  if (isNaN(playerId)) {
    notFound()
  }

  const player = await prisma.player.findUnique({
    where: { id: playerId },
    include: {
      // Get upcoming matches
      matchesAsP1: {
        where: { playedAt: { gte: new Date() } },
        include: {
          event: true,
          player1P1: true,
          player1P2: true,
          player2P1: true,
          player2P2: true,
        },
        orderBy: { playedAt: "asc" },
      },
      matchesAsP2: {
        where: { playedAt: { gte: new Date() } },
        include: {
          event: true,
          player1P1: true,
          player1P2: true,
          player2P1: true,
          player2P2: true,
        },
        orderBy: { playedAt: "asc" },
      },
      matchesAsP3: {
        where: { playedAt: { gte: new Date() } },
        include: {
          event: true,
          player1P1: true,
          player1P2: true,
          player2P1: true,
          player2P2: true,
        },
        orderBy: { playedAt: "asc" },
      },
      matchesAsP4: {
        where: { playedAt: { gte: new Date() } },
        include: {
          event: true,
          player1P1: true,
          player1P2: true,
          player2P1: true,
          player2P2: true,
        },
        orderBy: { playedAt: "asc" },
      },
    },
  })

  if (!player) {
    notFound()
  }

  // Combine all upcoming matches
  const upcomingMatches = [
    ...player.matchesAsP1,
    ...player.matchesAsP2,
    ...player.matchesAsP3,
    ...player.matchesAsP4,
  ].sort((a, b) => new Date(a.playedAt!).getTime() - new Date(b.playedAt!).getTime())

  // Get active tournaments (events with status 'active' or 'in_progress')
  const activeTournaments = await prisma.event.findMany({
    where: {
      status: { in: ['active', 'in_progress', 'started'] },
      participants: {
        some: {
          playerId: playerId,
        },
      },
    },
    include: {
      participants: true,
    },
  })

  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">
          <h1 className="text-3xl font-bold text-gray-900 mb-6">
            My Schedule
          </h1>

          {/* Upcoming Matches */}
          <div className="bg-white shadow rounded-lg p-6 mb-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">
              Upcoming Matches
            </h2>

            {upcomingMatches.length === 0 ? (
              <p className="text-gray-500">No upcoming matches</p>
            ) : (
              <div className="space-y-4">
                {upcomingMatches.map((match) => {
                  const team1Players = [
                    match.player1P1?.name,
                    match.player1P2?.name,
                  ].filter(Boolean).join(" + ")
                  const team2Players = [
                    match.player2P1?.name,
                    match.player2P2?.name,
                  ].filter(Boolean).join(" + ")

                  return (
                    <Link
                      href={`/matches/${match.id}`}
                      key={match.id}
                      className="block border border-gray-200 rounded-lg p-4 hover:bg-gray-50 cursor-pointer"
                    >
                      <div className="flex justify-between items-center">
                        <div className="flex-1">
                          <p className="text-sm text-gray-500">
                            {match.event?.name || "Tournament"} - {match.playedAt?.toLocaleDateString()}
                          </p>
                          <p className="font-medium">
                            {team1Players} vs {team2Players}
                          </p>
                        </div>
                        <div className="flex items-center space-x-4">
                          <span className="text-gray-400">
                            {match.playedAt?.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                          </span>
                        </div>
                      </div>
                    </Link>
                  )
                })}
              </div>
            )}
          </div>

          {/* Active Tournaments */}
          <div className="bg-white shadow rounded-lg p-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">
              Active Tournaments
            </h2>

            {activeTournaments.length === 0 ? (
              <p className="text-gray-500">No active tournaments.</p>
            ) : (
              <div className="space-y-4">
                {activeTournaments.map((tournament) => {
                  // Since teams are now ephemeral, just check if player is a participant
                  const isParticipant = tournament.participants.some(
                    (p) => p.playerId === playerId
                  )

                  return (
                    <div
                      key={tournament.id}
                      className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50"
                    >
                      <div className="flex justify-between items-center">
                        <div>
                          <Link
                            href={`/tournaments/${tournament.id}`}
                            className="font-medium text-green-600 hover:text-green-900"
                          >
                            {tournament.name}
                          </Link>
                          <p className="text-sm text-gray-500">
                            {tournament.format} - {tournament.status}
                          </p>
                          {isParticipant && (
                            <p className="text-sm text-gray-600">
                              Participant in tournament
                            </p>
                          )}
                        </div>
                        <div className="text-right">
                          <p className="text-sm text-gray-500">
                            {new Date(tournament.eventDate || tournament.createdAt).toLocaleDateString()}
                          </p>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  )
}
