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

interface PageProps {
  params: {
    id: string;
  };
}

export default async function MatchDetailPage({ params }: PageProps) {
  const { id } = await params;
  const matchId = parseInt(id, 10);

  if (isNaN(matchId)) {
    notFound();
  }

  // Fetch match with all player data
  const match = await prisma.match.findUnique({
    where: { id: matchId },
    include: {
      player1P1: true,
      player1P2: true,
      player2P1: true,
      player2P2: true,
      event: true,
      eloSnapshots: {
        include: {
          player: true,
        },
        orderBy: {
          playerId: "asc",
        },
      },
    },
  });

  if (!match) {
    notFound();
  }

  // Calculate Elo changes from snapshots
  const eloChanges: { [playerId: number]: number } = {};
  match.eloSnapshots.forEach((snapshot) => {
    eloChanges[snapshot.playerId] = snapshot.ratingChange;
  });

  return (
    <div className="min-h-screen bg-gray-50">
      <Navigation />
      
      <main className="max-w-3xl mx-auto py-6 sm:px-6 lg:px-8">
        <div className="px-4 py-6 sm:px-0">
          {/* Header */}
          <div className="mb-6">
            <div className="flex items-center justify-between">
              <h1 className="text-3xl font-bold text-gray-900">
                Match #{match.id}
              </h1>
              <Link
                href="/matches"
                className="text-green-600 hover:text-green-900"
              >
                ← All Matches
              </Link>
            </div>
            
            {match.event && (
              <p className="mt-2 text-sm text-gray-600">
                Part of{" "}
                <Link
                  href={`/admin/tournaments/${match.event.id}`}
                  className="text-green-600 hover:text-green-900"
                >
                  {match.event.name}
                </Link>
              </p>
            )}
          </div>

          {/* Match Diagram */}
          <div className="bg-white shadow rounded-lg p-6 mb-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">Match Setup</h2>
            
            <div className="flex justify-center">
              <div className="relative p-8">
                {/* Table Square - Larger with more padding */}
                <div className="w-72 h-72 bg-amber-100 border-4 border-amber-600 rounded-xl relative shadow-lg">
                  {/* Top: Team 1 Player 1 */}
                  <div className="absolute top-0 left-0 right-0 h-1/2 flex flex-col justify-end items-center pb-8">
                    <div className="text-center bg-white/80 rounded-lg px-3 py-2 shadow-sm -mt-[20px]">
                      <p className="text-base font-semibold text-amber-900">
                        {match.player1P1?.name}
                      </p>
                      <p className="text-xs text-amber-700">
                        Elo: {match.player1P1?.currentElo}
                        {match.player1P1 && eloChanges[match.player1P1.id] !== undefined && (
                          <span className={eloChanges[match.player1P1.id] >= 0 ? "text-green-600 ml-1" : "text-red-600 ml-1"}>
                            ({eloChanges[match.player1P1.id] >= 0 ? "+" : ""}{eloChanges[match.player1P1.id]})
                          </span>
                        )}
                      </p>
                    </div>
                    <div className="text-xs text-amber-600 mt-2 font-medium">Team 1</div>
                  </div>

                  {/* Bottom: Team 1 Player 2 - teammate opposite Top */}
                  <div className="absolute bottom-0 left-0 right-0 h-1/2 flex flex-col justify-start items-center pt-8">
                    <div className="text-xs text-amber-600 mb-2 font-medium">Team 1</div>
                    <div className="text-center bg-white/80 rounded-lg px-3 py-2 shadow-sm mt-[10px]">
                      <p className="text-base font-semibold text-amber-900">
                        {match.player1P2?.name}
                      </p>
                      <p className="text-xs text-amber-700">
                        Elo: {match.player1P2?.currentElo}
                        {match.player1P2 && eloChanges[match.player1P2.id] !== undefined && (
                          <span className={eloChanges[match.player1P2.id] >= 0 ? "text-green-600 ml-1" : "text-red-600 ml-1"}>
                            ({eloChanges[match.player1P2.id] >= 0 ? "+" : ""}{eloChanges[match.player1P2.id]})
                          </span>
                        )}
                      </p>
                    </div>
                  </div>

                  {/* Left: Team 2 Player 1 */}
                  <div className="absolute left-0 top-0 bottom-0 w-1/2 flex flex-col justify-center items-center pl-8">
                    <div className="text-center bg-white/80 rounded-lg px-3 py-2 shadow-sm rotate-[-90deg] -ml-[20px]">
                      <p className="text-sm font-semibold text-red-900">
                        {match.player2P1?.name}
                      </p>
                      <p className="text-[11px] text-red-700">
                        Elo: {match.player2P1?.currentElo}
                        {match.player2P1 && eloChanges[match.player2P1.id] !== undefined && (
                          <span className={eloChanges[match.player2P1.id] >= 0 ? "text-green-600" : "text-red-600"}>
                            ({eloChanges[match.player2P1.id] >= 0 ? "+" : ""}{eloChanges[match.player2P1.id]})
                          </span>
                        )}
                      </p>
                    </div>
                  </div>

                  {/* Right: Team 2 Player 2 - teammate opposite Left */}
                  <div className="absolute right-0 top-0 bottom-0 w-1/2 flex flex-col justify-center items-center pr-8">
                    <div className="text-center bg-white/80 rounded-lg px-3 py-2 shadow-sm rotate-[90deg] -mr-[20px]">
                      <p className="text-sm font-semibold text-red-900">
                        {match.player2P2?.name}
                      </p>
                      <p className="text-[11px] text-red-700">
                        Elo: {match.player2P2?.currentElo}
                        {match.player2P2 && eloChanges[match.player2P2.id] !== undefined && (
                          <span className={eloChanges[match.player2P2.id] >= 0 ? "text-green-600" : "text-red-600"}>
                            ({eloChanges[match.player2P2.id] >= 0 ? "+" : ""}{eloChanges[match.player2P2.id]})
                          </span>
                        )}
                      </p>
                    </div>
                  </div>

                  {/* Score in Center */}
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="bg-white border-2 border-gray-300 rounded-lg px-6 py-3 shadow-md">
                      <div className="text-center">
                        <p className="text-xl font-bold text-amber-600">
                          {match.team1Score}
                        </p>
                        <p className="text-xs text-gray-500">Team 1</p>
                      </div>
                      <div className="text-center text-gray-400 text-lg">—</div>
                      <div className="text-center">
                        <p className="text-xl font-bold text-red-600">
                          {match.team2Score}
                        </p>
                        <p className="text-xs text-gray-500">Team 2</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Legend */}
            <div className="mt-4 flex justify-center gap-6 text-sm">
              <div className="flex items-center">
                <div className="w-3 h-3 bg-amber-100 border border-amber-600 rounded mr-2"></div>
                <span>Team 1</span>
              </div>
              <div className="flex items-center">
                <div className="w-3 h-3 bg-red-100 border border-red-600 rounded mr-2"></div>
                <span>Team 2</span>
              </div>
            </div>
          </div>

          {/* Match Details */}
          <div className="bg-white shadow rounded-lg p-6 mb-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">Match Details</h2>
            
            <dl className="grid grid-cols-2 gap-4">
              <div>
                <dt className="text-sm font-medium text-gray-500">Match ID</dt>
                <dd className="mt-1 text-sm text-gray-900">{match.id}</dd>
              </div>
              
              {match.playedAt && (
                <div>
                  <dt className="text-sm font-medium text-gray-500">Date Played</dt>
                  <dd className="mt-1 text-sm text-gray-900">
                    {new Date(match.playedAt).toLocaleDateString()}
                  </dd>
                </div>
              )}
              
              {match.event && (
                <div>
                  <dt className="text-sm font-medium text-gray-500">Tournament</dt>
                  <dd className="mt-1 text-sm text-gray-900">
                    <Link
                      href={`/admin/tournaments/${match.event.id}`}
                      className="text-green-600 hover:text-green-900"
                    >
                      {match.event.name}
                    </Link>
                  </dd>
                </div>
              )}
              
              <div>
                <dt className="text-sm font-medium text-gray-500">Match Type</dt>
                <dd className="mt-1 text-sm text-gray-900">
                  {match.isCasual ? "Casual" : "Tournament"}
                </dd>
              </div>
            </dl>
          </div>

          {/* Elo Changes */}
          <div className="bg-white shadow rounded-lg p-6">
            <h2 className="text-xl font-bold text-gray-900 mb-4">Elo Changes</h2>
            
            <div className="grid grid-cols-2 gap-4">
              {/* Team 1 */}
              <div className="bg-amber-50 rounded-md p-4">
                <h3 className="font-medium text-amber-900 mb-3">Team 1</h3>
                <div className="space-y-2">
                  <div className="flex justify-between items-center">
                    <span>{match.player1P1?.name}</span>
                    {match.player1P1 && (
                      <span className={eloChanges[match.player1P1.id] >= 0 ? "text-green-600" : "text-red-600"}>
                        {eloChanges[match.player1P1.id] >= 0 ? "+" : ""}{eloChanges[match.player1P1.id]}
                      </span>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <span>{match.player1P2?.name}</span>
                    {match.player1P2 && (
                      <span className={eloChanges[match.player1P2.id] >= 0 ? "text-green-600" : "text-red-600"}>
                        {eloChanges[match.player1P2.id] >= 0 ? "+" : ""}{eloChanges[match.player1P2.id]}
                      </span>
                    )}
                  </div>
                </div>
              </div>
              
              {/* Team 2 */}
              <div className="bg-red-50 rounded-md p-4">
                <h3 className="font-medium text-red-900 mb-3">Team 2</h3>
                <div className="space-y-2">
                  <div className="flex justify-between items-center">
                    <span>{match.player2P1?.name}</span>
                    {match.player2P1 && (
                      <span className={eloChanges[match.player2P1.id] >= 0 ? "text-green-600" : "text-red-600"}>
                        {eloChanges[match.player2P1.id] >= 0 ? "+" : ""}{eloChanges[match.player2P1.id]}
                      </span>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <span>{match.player2P2?.name}</span>
                    {match.player2P2 && (
                      <span className={eloChanges[match.player2P2.id] >= 0 ? "text-green-600" : "text-red-600"}>
                        {eloChanges[match.player2P2.id] >= 0 ? "+" : ""}{eloChanges[match.player2P2.id]}
                      </span>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
