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";
import InstanceActions from "./InstanceActions";
import Link from "next/link";
import { Button } from "@/components/ui/button";

export const dynamic = "force-dynamic";

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

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">Instances</h1>
        <Link href="/dashboard/instances/assign">
          <Button>Attribuer une instance</Button>
        </Link>
      </div>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>ID</TableHead>
                <TableHead>Template</TableHead>
                <TableHead>Nœud</TableHead>
                <TableHead>Étudiant</TableHead>
                <TableHead>Port</TableHead>
                <TableHead>Statut</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {instances.map((inst) => (
                <TableRow key={inst.id}>
                  <TableCell className="font-medium">{inst.id.slice(0, 8)}...</TableCell>
                  <TableCell>{inst.template.name}</TableCell>
                  <TableCell>{inst.node.id.slice(0, 8)}...</TableCell>
                  <TableCell>{inst.node.student ? `${inst.node.student.firstName} ${inst.node.student.lastName}` : "-"}</TableCell>
                  <TableCell>{inst.port}</TableCell>
                  <TableCell>
                    <Badge variant={inst.status === "running" ? "success" : inst.status === "error" ? "destructive" : "secondary"}>{inst.status}</Badge>
                  </TableCell>
                  <TableCell>
                    <InstanceActions instanceId={inst.id} status={inst.status} />
                  </TableCell>
                </TableRow>
              ))}
              {instances.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground">Aucune instance</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
