import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { requirePermission } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/utils";

type AdminPostViewPageProps = {
  params: Promise<{ id: string }>;
};

export default async function AdminPostViewPage({ params }: AdminPostViewPageProps) {
  const session = await requirePermission("posts");
  const { id } = await params;
  const post = await prisma.post.findUnique({
    include: { category: true, author: true },
    where: { id }
  });

  if (!post) {
    notFound();
  }

  return (
      <>

      <div className="section-head">
        <div>
          <span className="pill">Blog Preview</span>
          <h1 className="admin-title">{post.title}</h1>
          <p className="muted">
            {post.category?.name ?? "No category"} · {post.status} · {post.approvalStatus} · Updated {formatDate(post.updatedAt)}
          </p>
        </div>
        <Link className="btn btn-secondary" href={`/admin/posts/${post.id}`}>Update</Link>
      </div>

      <article className="glass-panel" style={{ display: "grid", gap: "1.25rem" }}>
        {post.coverImage ? (
          <div className="article-cover-image" style={{ margin: 0 }}>
            <Image alt={post.title} fill sizes="(max-width: 900px) 100vw, 900px" src={post.coverImage} unoptimized />
          </div>
        ) : null}
        <p className="muted" style={{ fontSize: "1.05rem", lineHeight: 1.8 }}>{post.excerpt}</p>
        <div style={{ lineHeight: 1.9, whiteSpace: "pre-wrap" }}>{post.content}</div>
        {post.rejectionReason ? <p className="admin-error-message">{post.rejectionReason}</p> : null}
      </article>
      </>
    );
}
