import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth-config";
import { redirect, notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { DeleteClassDialog } from "./DeleteClassDialog";

export const dynamic = "force-dynamic";

export default async function ClassDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");
  if (!session.user.establishmentId && session.user.role !== "superadmin") redirect("/dashboard");

  const establishmentId = session.user.establishmentId;
  const cls = await prisma.class.findFirst({
    where: { id, ...(establishmentId ? { establishmentId } : {}) },
    include: { students: true },
  });

  if (!cls) notFound();

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">{cls.name}</h1>
        <DeleteClassDialog classId={cls.id} className={cls.name} />
      </div>
      <Card>
        <CardContent className="pt-6 space-y-4">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">Niveau :</span>
            <Badge variant="secondary">{cls.level}</Badge>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">Étudiants :</span>
            <span>{cls.students.length}</span>
          </div>
        </CardContent>
      </Card>

      <h2 className="text-2xl font-bold">Étudiants</h2>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nom</TableHead>
                <TableHead>Email</TableHead>
                <TableHead>Code activation</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {cls.students.map((s) => (
                <TableRow key={s.id}>
                  <TableCell className="font-medium">{s.firstName} {s.lastName}</TableCell>
                  <TableCell>{s.email}</TableCell>
                  <TableCell>{s.activationCode || "-"}</TableCell>
                </TableRow>
              ))}
              {cls.students.length === 0 && (
                <TableRow>
                  <TableCell colSpan={3} className="text-center text-muted-foreground">Aucun étudiant</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
