export const dynamic = "force-dynamic";

import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Select } from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import { updateSubscription, deleteEstablishment, createAdmin, deleteAdmin } from "./actions";
import { DeleteDialog } from "./delete-dialog";

export default async function EstablishmentDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const establishment = await prisma.establishment.findUnique({
    where: { id },
    include: {
      subscription: true,
      _count: { select: { users: true, classes: true } },
    },
  });

  if (!establishment) notFound();

  const admins = await prisma.user.findMany({
    where: { establishmentId: id, role: "admin" },
    orderBy: { createdAt: "desc" },
  });

  const boundDelete = deleteEstablishment.bind(null, establishment.id);
  const boundCreateAdmin = createAdmin.bind(null, establishment.id);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-3xl font-bold">{establishment.name}</h1>
        <div className="flex items-center gap-2">
          <Button variant="outline" asChild>
            <Link href="/superadmin/establishments">Retour</Link>
          </Button>
          <DeleteDialog deleteAction={boundDelete} />
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>Informations</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">Slug</span>
              <span className="font-medium">{establishment.slug}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">Utilisateurs</span>
              <span className="font-medium">{establishment._count.users}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">Classes</span>
              <span className="font-medium">{establishment._count.classes}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">Créé le</span>
              <span className="font-medium">
                {new Date(establishment.createdAt).toLocaleDateString("fr-FR")}
              </span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Abonnement</CardTitle>
          </CardHeader>
          <CardContent>
            <form action={updateSubscription.bind(null, establishment.id)} className="space-y-4">
              <div className="space-y-2">
                <label htmlFor="plan" className="text-sm font-medium">
                  Plan
                </label>
                <Select
                  id="plan"
                  name="plan"
                  defaultValue={establishment.subscription?.plan || "trial"}
                >
                  <option value="trial">Trial</option>
                  <option value="starter">Starter</option>
                  <option value="standard">Standard</option>
                  <option value="premium">Premium</option>
                </Select>
              </div>
              <div className="space-y-2">
                <label htmlFor="status" className="text-sm font-medium">
                  Statut
                </label>
                <Select
                  id="status"
                  name="status"
                  defaultValue={establishment.subscription?.status || "active"}
                >
                  <option value="active">Active</option>
                  <option value="suspended">Suspended</option>
                  <option value="expired">Expired</option>
                </Select>
              </div>
              <div className="flex items-center justify-between">
                <Badge variant={establishment.subscription?.status === "active" ? "success" : "destructive"}>
                  {establishment.subscription?.status || "-"}
                </Badge>
                <Button type="submit">Mettre à jour</Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Administrateurs</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          <form action={boundCreateAdmin} className="grid gap-4 md:grid-cols-3 items-end">
            <div className="space-y-2">
              <label htmlFor="email" className="text-sm font-medium">Email</label>
              <Input id="email" name="email" type="email" required />
            </div>
            <div className="space-y-2">
              <label htmlFor="password" className="text-sm font-medium">Mot de passe</label>
              <Input id="password" name="password" type="password" required minLength={8} />
            </div>
            <Button type="submit">Créer un admin</Button>
          </form>

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Email</TableHead>
                <TableHead>Rôle</TableHead>
                <TableHead>Créé le</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {admins.map((user) => (
                <TableRow key={user.id}>
                  <TableCell className="font-medium">{user.email}</TableCell>
                  <TableCell><Badge variant="secondary">{user.role}</Badge></TableCell>
                  <TableCell>{new Date(user.createdAt).toLocaleDateString("fr-FR")}</TableCell>
                  <TableCell className="text-right">
                    <form action={deleteAdmin.bind(null, establishment.id, user.id)}>
                      <Button type="submit" variant="destructive" size="sm">Supprimer</Button>
                    </form>
                  </TableCell>
                </TableRow>
              ))}
              {admins.length === 0 && (
                <TableRow>
                  <TableCell colSpan={4} className="text-center text-muted-foreground">
                    Aucun administrateur
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
