import { prisma } from "@/lib/prisma"
import Link from "next/link"
import Navigation from "@/components/Navigation"

export const dynamic = "force-dynamic"

export default async function Home() {
  // Fetch top 10 players by Elo rating
  const topPlayers = await prisma.player.findMany({
    orderBy: { currentElo: "desc" },
    take: 10,
    include: {
      partnershipStats: true,
      partnershipStats2: true,
    },
  })

  // Fetch most recent tournament
  const mostRecentTournament = await prisma.event.findFirst({
    where: { 
      eventType: "tournament",
      status: { not: "draft" }
    },
    orderBy: { eventDate: "desc" },
    include: {
      matches: {
        include: {
          player1P1: true,
          player1P2: true,
          player2P1: true,
          player2P2: true,
        },
        orderBy: { playedAt: "desc" },
      },
    },
  })

  // Fetch club president (first user with club_admin role)
  const clubPresident = await prisma.user.findFirst({
    where: { role: "club_admin" },
    select: { name: true, email: true },
  })

  // Calculate win rates for top players
  const playersWithWinRates = topPlayers.map((player) => ({
    ...player,
    winRate: player.gamesPlayed > 0
      ? (player.wins / player.gamesPlayed) * 100
      : 0,
  }))

  return (
    <div className="min-h-screen bg-gradient-to-br from-green-50 to-blue-50">
      <Navigation />
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        {/* Header Section */}
        <div className="text-center mb-12">
          <h1 className="text-4xl md:text-5xl font-extrabold text-gray-900 mb-4">
            EuchreCamp
          </h1>
          <p className="text-xl text-gray-600 mb-8 max-w-3xl mx-auto">
            Track your Euchre games, tournaments, and partnership performance
            with our comprehensive tournament management system.
          </p>
          
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <Link
              href="/auth/login"
              className="px-8 py-3 bg-green-600 text-white rounded-lg font-semibold hover:bg-green-700 transition-colors"
            >
              Sign In
            </Link>
            <Link
              href="/auth/register"
              className="px-8 py-3 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors"
            >
              Create Account
            </Link>
          </div>
        </div>

        {/* Top 10 Players Section */}
        <div className="bg-white shadow rounded-lg p-6 mb-8">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">
            Top 10 Players
          </h2>
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Rank
                  </th>
                  <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Player
                  </th>
                  <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Elo Rating
                  </th>
                  <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Games
                  </th>
                  <th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Win Rate
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {playersWithWinRates.map((player, index) => (
                  <tr key={player.id} className="hover:bg-gray-50">
                    <td className="px-4 py-2 whitespace-nowrap text-sm font-medium text-gray-900">
                      {index + 1}
                    </td>
                    <td className="px-4 py-2 whitespace-nowrap">
                      <Link
                        href={`/players/${player.id}/profile`}
                        className="text-green-600 hover:text-green-900"
                      >
                        {player.name}
                      </Link>
                    </td>
                    <td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900">
                      {player.currentElo}
                    </td>
                    <td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                      {player.gamesPlayed}
                    </td>
                    <td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
                      {player.gamesPlayed > 0
                        ? `${player.winRate.toFixed(1)}%`
                        : "N/A"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="mt-4 text-center">
            <Link
              href="/rankings"
              className="text-green-600 hover:text-green-900 font-medium"
            >
              View Full Rankings →
            </Link>
          </div>
        </div>

        {/* Most Recent Tournament Section */}
        {mostRecentTournament && (
          <div className="bg-white shadow rounded-lg p-6 mb-8">
            <h2 className="text-2xl font-bold text-gray-900 mb-4">
              Most Recent Tournament
            </h2>
            <div className="mb-4">
              <h3 className="text-xl font-semibold text-gray-800">
                {mostRecentTournament.name}
              </h3>
              {mostRecentTournament.eventDate && (
                <p className="text-gray-600">
                  {new Date(mostRecentTournament.eventDate).toLocaleDateString()}
                </p>
              )}
              <p className="text-sm text-gray-500">
                Status: {mostRecentTournament.status}
              </p>
            </div>

            {/* Tournament Matches */}
            <div className="mt-6">
              <h4 className="text-lg font-medium text-gray-900 mb-3">
                Matches ({mostRecentTournament.matches.length})
              </h4>
              <div className="space-y-3 max-h-96 overflow-y-auto">
                {mostRecentTournament.matches.map((match) => (
                  <Link
                    key={match.id}
                    href={`/matches/${match.id}`}
                    className="block bg-gray-50 rounded-lg p-4 border border-gray-200 hover:border-green-300 hover:bg-green-50 transition-colors"
                  >
                    <div className="flex justify-between items-center">
                      <div className="flex-1 text-center">
                        <div className="text-sm font-medium text-gray-900">
                          {match.player1P1?.name} & {match.player1P2?.name}
                        </div>
                        <div className="text-lg font-bold text-gray-800">
                          {match.team1Score}
                        </div>
                      </div>
                      <div className="px-3 text-gray-500">vs</div>
                      <div className="flex-1 text-center">
                        <div className="text-sm font-medium text-gray-900">
                          {match.player2P1?.name} & {match.player2P2?.name}
                        </div>
                        <div className="text-lg font-bold text-gray-800">
                          {match.team2Score}
                        </div>
                      </div>
                    </div>
                    <div className="mt-2 text-center text-sm text-gray-500">
                      {match.playedAt && (
                        <span>
                          {new Date(match.playedAt).toLocaleDateString()} at{' '}
                          {new Date(match.playedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      )}
                    </div>
                  </Link>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Club President Section */}
        <div className="bg-white shadow rounded-lg p-6">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">
            Club Information
          </h2>
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                <svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
              </div>
            </div>
            <div className="ml-4">
              <h3 className="text-lg font-medium text-gray-900">Club President</h3>
              <p className="text-gray-600">
                {clubPresident?.name || clubPresident?.email || "Not assigned"}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
