import { prisma } from "@/lib/prisma"
import Navigation from "@/components/Navigation"
import Link from "next/link"
import { redirect } from "next/navigation"
import { getSession } from "@/lib/auth-simple"
import { hasRole } from "@/lib/permissions"
import UserActions from "./components/UserActions"

export const dynamic = "force-dynamic";

export default async function AdminUsersPage() {
  // Check permissions
  const permission = await hasRole("club_admin");
  if (!permission.allowed) {
    redirect("/auth/login");
  }

  const session = await getSession();
  const userId = session?.user?.id || session?.user?.userId;
  
  // Check if user is site_admin for delete permissions
  const isSiteAdmin = await hasRole("site_admin");

  // Fetch all users with their associated players
  const users = await prisma.user.findMany({
    orderBy: { createdAt: "desc" },
    include: {
      player: true,
    },
  });

  // Fetch all players without associated users
  const playersWithoutUsers = await prisma.player.findMany({
    where: {
      user: null,
    },
    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">
          {/* Page Header */}
          <div className="bg-white shadow rounded-lg p-6 mb-6">
            <div className="flex items-center justify-between">
              <div>
                <h1 className="text-2xl font-bold text-gray-900">User Management</h1>
                <p className="text-gray-500 mt-1">
                  Create users and associate them with players.
                </p>
              </div>
              <Link
                href="/admin/users/create"
                className="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors"
              >
                + Create User
              </Link>
            </div>
          </div>

          {/* Users List */}
          <div className="bg-white shadow rounded-lg overflow-hidden">
            <div className="px-6 py-4 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">All Users</h2>
            </div>
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Email
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Name
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Role
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Associated Player
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Created
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {users.map((user) => (
                    <tr key={user.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        {user.email}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {user.name || "-"}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`px-2 py-1 text-xs font-medium rounded-full ${
                          user.role === 'site_admin' ? 'bg-purple-100 text-purple-800' :
                          user.role === 'club_admin' ? 'bg-blue-100 text-blue-800' :
                          user.role === 'tournament_admin' ? 'bg-green-100 text-green-800' :
                          'bg-gray-100 text-gray-800'
                        }`}>
                          {user.role}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {user.player ? (
                          <Link
                            href={`/players/${user.player.id}/profile`}
                            className="text-green-600 hover:text-green-900"
                          >
                            {user.player.name}
                          </Link>
                        ) : (
                          <span className="text-gray-400">Not assigned</span>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {new Date(user.createdAt).toLocaleDateString()}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm">
                        <UserActions 
                          userId={user.id} 
                          isSiteAdmin={isSiteAdmin.allowed} 
                          currentUserId={userId || ""} 
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Players without users */}
          {playersWithoutUsers.length > 0 && (
            <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mt-6">
              <h3 className="text-sm font-medium text-yellow-800 mb-2">
                Players without associated users
              </h3>
              <p className="text-sm text-yellow-700 mb-3">
                The following players exist but don't have an associated user account.
              </p>
              <ul className="text-sm text-yellow-700">
                {playersWithoutUsers.slice(0, 5).map((player) => (
                  <li key={player.id} className="flex items-center justify-between">
                    <span>{player.name}</span>
                    <Link
                      href={`/admin/users/create?playerId=${player.id}`}
                      className="text-yellow-800 hover:text-yellow-900 underline"
                    >
                      Create user for this player
                    </Link>
                  </li>
                ))}
                {playersWithoutUsers.length > 5 && (
                  <li className="text-yellow-600">
                    ...and {playersWithoutUsers.length - 5} more
                  </li>
                )}
              </ul>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}
