import { getServerSession } from "next-auth";
import { notFound } from "next/navigation";
import { authOptions } from "../../../lib/auth/options";
import { prisma } from "../../../lib/db/prisma";
import { AuditPanel } from "../../components/audit-panel";
import { TeamActions } from "../team-actions";
import { TeamEditForm } from "../team-edit-form";

export default async function TeamDetailsPage({ params }: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  const organizationId = session?.user.systemRole === "SYSTEM_ADMIN" ? undefined : session?.user.organizationId!;
  const [team, users] = await Promise.all([
    prisma.team.findFirst({
      where: { id: params.id, ...(organizationId ? { organizationId } : {}) },
      include: { users: { include: { roles: true, projects: true } } }
    }),
    prisma.user.findMany({ where: organizationId ? { organizationId } : {}, orderBy: { name: "asc" } })
  ]);
  if (!team) notFound();

  return (
    <div>
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <h1 className="text-3xl font-semibold">{team.name}</h1>
          <p className="mt-2 text-slate-600">Users assigned to this team.</p>
        </div>
        <TeamActions id={team.id} userCount={team.users.length} />
      </div>
      <TeamEditForm team={team} users={users} />
      <section className="mt-6 rounded-lg border border-brand-primary/20 bg-white p-5 shadow-sm">
        <table className="w-full text-left text-sm">
          <thead className="text-slate-500"><tr><th className="py-2">User</th><th>Email</th><th>Roles</th><th>Projects</th></tr></thead>
          <tbody>
            {team.users.map((user) => (
              <tr className="border-t border-slate-200" key={user.id}>
                <td className="py-3">{user.name}</td>
                <td>{user.email}</td>
                <td>{user.roles.map((role) => role.name).join(", ")}</td>
                <td>{user.projects.map((project) => project.name).join(", ") || "-"}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </section>
      <AuditPanel targetId={team.id} targetType="team" title="Team audit events" />
    </div>
  );
}
