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

export const dynamic = "force-dynamic";

export default async function DashboardPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");

  const isSuperadmin = session.user.role === "superadmin";
  const establishmentId = session.user.establishmentId;

  const where = isSuperadmin ? {} : { establishmentId };

  const nodesCount = await prisma.node.count({
    where: isSuperadmin ? {} : { student: { class: { establishmentId } } },
  });
  const onlineNodes = await prisma.node.count({
    where: isSuperadmin ? { status: "online" } : { status: "online", student: { class: { establishmentId } } },
  });
  const instancesRunning = await prisma.instance.count({
    where: isSuperadmin ? { status: "running" } : { status: "running", node: { student: { class: { establishmentId } } } },
  });
  const studentsCount = await prisma.student.count({
    where: isSuperadmin ? {} : { class: { establishmentId } },
  });

  return (
    <div className="space-y-6">
      <h1 className="text-3xl font-bold">Tableau de bord</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Nœuds</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold">{nodesCount}</div>
            <Badge variant="success" className="mt-2">{onlineNodes} en ligne</Badge>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Instances actives</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold">{instancesRunning}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Étudiants</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold">{studentsCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Statut</CardTitle>
          </CardHeader>
          <CardContent>
            <Badge variant="success">Opérationnel</Badge>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
