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

export const dynamic = "force-dynamic";

export default async function UserDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login");

  const isSuperadmin = session.user.role === "superadmin";
  if (!isSuperadmin && session.user.role !== "admin") redirect("/dashboard");

  const user = await prisma.user.findUnique({
    where: { id },
    include: { establishment: true },
  });

  if (!user) notFound();

  if (!isSuperadmin && user.establishmentId !== session.user.establishmentId) {
    redirect("/dashboard/users");
  }

  return (
    <div className="space-y-6 max-w-xl">
      <h1 className="text-3xl font-bold">Détail de l'utilisateur</h1>
      <Card>
        <CardHeader>
          <CardTitle>{user.email}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">Rôle :</span>
            <Badge
              variant={
                user.role === "superadmin"
                  ? "default"
                  : user.role === "admin"
                  ? "secondary"
                  : "outline"
              }
            >
              {user.role}
            </Badge>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">Établissement :</span>
            <span>{user.establishment?.name || "-"}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-muted-foreground">Créé le :</span>
            <span>{new Date(user.createdAt).toLocaleDateString("fr-FR")}</span>
          </div>
          <div className="flex gap-2 pt-4">
            <Link href="/dashboard/users">
              <Button variant="outline">Retour</Button>
            </Link>
            <DeleteUserButton userId={user.id} currentUserId={session.user.id as string} />
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
