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

export const dynamic = "force-dynamic";

export default async function NodesPage() {
  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 nodes = await prisma.node.findMany({
    where: establishmentId
      ? { student: { class: { establishmentId } } }
      : {},
    include: { student: { include: { class: true } }, instances: true },
    orderBy: { lastSeen: "desc" },
  });

  return (
    <div className="space-y-6">
      <h1 className="text-3xl font-bold">Nœuds</h1>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>ID</TableHead>
                <TableHead>Étudiant</TableHead>
                <TableHead>IP Tailscale</TableHead>
                <TableHead>Statut</TableHead>
                <TableHead>Instances</TableHead>
                <TableHead>Dernière vue</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {nodes.map((n) => (
                <TableRow key={n.id}>
                  <TableCell className="font-medium">{n.id}</TableCell>
                  <TableCell>{n.student ? `${n.student.firstName} ${n.student.lastName}` : "-"}</TableCell>
                  <TableCell>{n.tailscaleIp || "-"}</TableCell>
                  <TableCell>
                    <Badge variant={n.status === "online" ? "success" : "secondary"}>{n.status}</Badge>
                  </TableCell>
                  <TableCell>{n.instances.length}</TableCell>
                  <TableCell>{n.lastSeen ? new Date(n.lastSeen).toLocaleString("fr-FR") : "-"}</TableCell>
                </TableRow>
              ))}
              {nodes.length === 0 && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground">Aucun nœud</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
