import Link from "next/link";
import { AdminRowActions } from "@/admin/components/AdminRowActions";
import { deletePostAction } from "@/lib/actions";
import { isSuperAdmin, requirePermission } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/utils";

export default async function AdminPostsPage() {
  const session = await requirePermission("posts");
  const superAdmin = isSuperAdmin(session);
  const posts = await prisma.post.findMany({
    include: { category: true, author: true },
    orderBy: { updatedAt: "desc" }
  });

  return (
    <>
      <div className="section-head">
        <div>
          <span className="pill">Editorial database</span>
          <h1 className="admin-title">Articles</h1>
          {superAdmin ? <p className="muted">Super Admin can view, modify, or delete any article.</p> : null}
        </div>
        <Link className="btn" href="/admin/posts/new">
          New Article
        </Link>
      </div>
      <div className="glass-panel data-table-wrap">
        <table className="data-table">
          <thead>
            <tr>
              <th align="left">Title</th>
              <th align="left">Category</th>
              <th align="left">Status</th>
              <th align="left">Approval</th>
              <th align="left">Updated</th>
              <th align="left">Actions</th>
            </tr>
          </thead>
          <tbody>
            {posts.map((post) => (
              <tr key={post.id}>
                <td>{post.title}</td>
                <td>{post.category?.name ?? "-"}</td>
                <td>
                  <span className="status-badge">{post.status}</span>
                </td>
                <td>
                  <span className="status-badge">{post.approvalStatus}</span>
                </td>
                <td>{formatDate(post.updatedAt)}</td>
                <td>
                  <AdminRowActions
                    deleteAction={deletePostAction}
                    deleteConfirm={`Delete article "${post.title}"? This cannot be undone.`}
                    deleteId={post.id}
                    modifyHref={`/admin/posts/${post.id}`}
                    viewHref={`/admin/posts/${post.id}/view`}
                  />
                </td>
              </tr>
            ))}
            {posts.length === 0 ? (
              <tr>
                <td colSpan={6}>
                  <p className="admin-empty-state">No articles yet. Create your first blog post to get started.</p>
                </td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </div>
    </>
  );
}
