import { prisma } from "@/lib/prisma"
import Navigation from "@/components/Navigation"
import Link from "next/link"
import { redirect } from "next/navigation"
import { hasRole } from "@/lib/permissions"
import EditUserForm from "@/app/admin/users/components/EditUserForm"

export const dynamic = "force-dynamic";

export default async function EditUserPage({
  params,
}: {
  params: { id: string };
}) {
  // Check permissions
  const permission = await hasRole("club_admin");
  if (!permission.allowed) {
    redirect("/auth/login");
  }

  const { id } = params;

  // Get user info
  const user = await prisma.user.findUnique({
    where: { id },
    include: {
      player: true,
    },
  });

  if (!user) {
    redirect("/admin/users");
  }

  // Get all players without associated users (excluding the current user's player)
  const availablePlayers = await prisma.player.findMany({
    where: {
      OR: [
        { user: null },
        ...(user.playerId ? [{ id: user.playerId }] : []), // Include the currently associated player if any
      ],
    },
    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">Edit User</h1>
                <p className="text-gray-500 mt-1">
                  Update user account and player association.
                </p>
              </div>
              <Link
                href="/admin/users"
                className="text-gray-600 hover:text-gray-900"
              >
                ← Back to Users
              </Link>
            </div>
          </div>

          {/* Edit User Form */}
          <div className="bg-white shadow rounded-lg p-6">
            <EditUserForm 
              user={user}
              availablePlayers={availablePlayers}
            />
          </div>
        </div>
      </main>
    </div>
  );
}
