import { prisma } from "@/lib/prisma";
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 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">
      <h1 className="text-3xl font-bold">Établissements</h1>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nom</TableHead>
                <TableHead>Slug</TableHead>
                <TableHead>Plan</TableHead>
                <TableHead>Statut</TableHead>
                <TableHead>Utilisateurs</TableHead>
                <TableHead>Classes</TableHead>
                <TableHead>Expiration</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {establishments.map((e) => (
                <TableRow key={e.id}>
                  <TableCell className="font-medium">{e.name}</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>
                  <TableCell>{e.subscription?.expiresAt ? new Date(e.subscription.expiresAt).toLocaleDateString("fr-FR") : "-"}</TableCell>
                </TableRow>
              ))}
              {establishments.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground">Aucun établissement</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
