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

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

  return (
    <>
      <div className="section-head">
        <div>
          <span className="pill">Video command</span>
          <h1 className="admin-title">Videos</h1>
          {superAdmin ? <p className="muted">Super Admin can view, modify, or delete any video.</p> : null}
        </div>
        <Link className="btn" href="/admin/videos/new">
          New Video
        </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>
            {videos.map((video) => (
              <tr key={video.id}>
                <td>{video.title}</td>
                <td>{video.category?.name ?? "-"}</td>
                <td>
                  <span className="status-badge">{video.status}</span>
                </td>
                <td>
                  <span className="status-badge">{video.approvalStatus}</span>
                </td>
                <td>{formatDate(video.updatedAt)}</td>
                <td>
                  <AdminRowActions
                    deleteAction={deleteVideoAction}
                    deleteConfirm={`Delete video "${video.title}"? This cannot be undone.`}
                    deleteId={video.id}
                    modifyHref={`/admin/videos/${video.id}`}
                    viewHref={video.slug ? `/videos/${video.slug}` : undefined}
                  />
                </td>
              </tr>
            ))}
            {videos.length === 0 ? (
              <tr>
                <td colSpan={6}>
                  <p className="admin-empty-state">No videos yet. Add a YouTube video to start building the library.</p>
                </td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </div>
    </>
  );
}
