export const dynamic = "force-dynamic";

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

export default async function EstablishmentsPage() {
  const establishments = await prisma.establishment.findMany({
    include: {
      subscription: true,
      _count: { select: { users: true, classes: true } },
    },
    orderBy: { createdAt: "desc" },
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">Établissements</h1>
        <Button asChild>
          <Link href="/superadmin/establishments/new">Ajouter</Link>
        </Button>
      </div>
      <Card>
        <CardHeader>
          <CardTitle>Liste des établissements</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nom</TableHead>
                <TableHead>Slug</TableHead>
                <TableHead>Plan</TableHead>
                <TableHead>Statut</TableHead>
                <TableHead>Utilisateurs</TableHead>
                <TableHead>Classes</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {establishments.map((e) => (
                <TableRow key={e.id}>
                  <TableCell className="font-medium">
                    <Link href={`/superadmin/establishments/${e.id}`} className="hover:underline">
                      {e.name}
                    </Link>
                  </TableCell>
                  <TableCell>{e.slug}</TableCell>
                  <TableCell>
                    <Badge variant="secondary">{e.subscription?.plan || "-"}</Badge>
                  </TableCell>
                  <TableCell>
                    <Badge variant={e.subscription?.status === "active" ? "success" : "destructive"}>
                      {e.subscription?.status || "-"}
                    </Badge>
                  </TableCell>
                  <TableCell>{e._count.users}</TableCell>
                  <TableCell>{e._count.classes}</TableCell>
                </TableRow>
              ))}
              {establishments.length === 0 && (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground">
                    Aucun établissement
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
