import Link from "next/link";
import { AdminAnalyticsChart } from "@/admin/components/AdminAnalyticsChart";
import { reviewContentAction } from "@/lib/actions";
import { isSuperAdmin, requireAdmin } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/utils";

export default async function AdminDashboardPage() {
  const session = await requireAdmin();
  const [postCount, videoCount, messages, latestPosts, latestVideos, pendingPosts, pendingVideos, pendingGallery, ownRejectedPosts, ownRejectedVideos, ownRejectedGallery] = await Promise.all([
    prisma.post.count(),
    prisma.video.count(),
    prisma.contactMessage.findMany({ orderBy: { createdAt: "desc" }, take: 5 }),
    prisma.post.findMany({ orderBy: { updatedAt: "desc" }, take: 5 }),
    prisma.video.findMany({ orderBy: { updatedAt: "desc" }, take: 5 }),
    prisma.post.findMany({ where: { approvalStatus: "PENDING" }, include: { author: true }, orderBy: { updatedAt: "desc" }, take: 10 }),
    prisma.video.findMany({ where: { approvalStatus: "PENDING" }, include: { author: true }, orderBy: { updatedAt: "desc" }, take: 10 }),
    prisma.galleryImage.findMany({ where: { approvalStatus: "PENDING" }, include: { author: true }, orderBy: { updatedAt: "desc" }, take: 10 }),
    prisma.post.findMany({ where: { authorId: session.id, approvalStatus: "REJECTED" }, orderBy: { updatedAt: "desc" }, take: 5 }),
    prisma.video.findMany({ where: { authorId: session.id, approvalStatus: "REJECTED" }, orderBy: { updatedAt: "desc" }, take: 5 }),
    prisma.galleryImage.findMany({ where: { authorId: session.id, approvalStatus: "REJECTED" }, orderBy: { updatedAt: "desc" }, take: 5 })
  ]);
  const pendingCount = pendingPosts.length + pendingVideos.length + pendingGallery.length;
  const userPendingPosts = pendingPosts.filter((post) => post.author?.role === "USER");
  const staffPendingPosts = pendingPosts.filter((post) => post.author?.role !== "USER");
  const userPendingVideos = pendingVideos.filter((video) => video.author?.role === "USER");
  const staffPendingVideos = pendingVideos.filter((video) => video.author?.role !== "USER");
  const userPendingGallery = pendingGallery.filter((image) => image.author?.role === "USER");
  const staffPendingGallery = pendingGallery.filter((image) => image.author?.role !== "USER");
  const ownRejected = [
    ...ownRejectedPosts.map((item) => ({ id: item.id, reason: item.rejectionReason, title: item.title, type: "Blog" })),
    ...ownRejectedVideos.map((item) => ({ id: item.id, reason: item.rejectionReason, title: item.title, type: "Video" })),
    ...ownRejectedGallery.map((item) => ({ id: item.id, reason: item.rejectionReason, title: item.title, type: "Gallery" }))
  ];
  const chartLabels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"];
  const chartValues = [
    Math.max(postCount - 5, 1),
    Math.max(postCount - 3, 2),
    Math.max(postCount - 2, 3),
    Math.max(postCount - 1, 4),
    postCount,
    postCount + videoCount
  ];
  const tableRows = [
    ...latestPosts.map((post) => ({
      date: post.updatedAt,
      href: `/admin/posts/${post.id}`,
      status: post.status,
      title: post.title,
      type: "Article"
    })),
    ...latestVideos.map((video) => ({
      date: video.updatedAt,
      href: `/admin/videos/${video.id}`,
      status: video.status,
      title: video.title,
      type: "Video"
    }))
  ]
    .sort((a, b) => b.date.getTime() - a.date.getTime())
    .slice(0, 8);

  return (
      <>

      {isSuperAdmin(session) ? null : (
        <p className="admin-success-message" style={{ marginBottom: 20 }}>
          Staff mode active. You can access only the sections assigned by Super Admin.
        </p>
      )}
      <section className="admin-dashboard-head">
        <div>
          <h1>Dashboard</h1>
          <p>Welcome back, {session.name}. Here&apos;s what&apos;s happening with your website today.</p>
        </div>
        <Link className="btn btn-secondary" href="/">Open Website</Link>
      </section>

      <section className="admin-kpi-grid">
        <DashboardMetric label="Blog Posts" tone="green" value={postCount} />
        <DashboardMetric label="Videos" tone="cyan" value={videoCount} />
        <DashboardMetric label="Messages" tone="amber" value={messages.length} />
        <DashboardMetric label="Pending Reviews" tone="red" value={pendingCount} />
      </section>

      <section className="admin-overview-card admin-chart-panel">
        <div className="admin-panel-heading">
          <div>
            <span className="pill">Overview</span>
            <h2>Monthly website activity</h2>
          </div>
          <div className="admin-tabs">
            <span className="active">Content</span>
            <span>Messages</span>
            <span>Approvals</span>
          </div>
        </div>
        <AdminAnalyticsChart labels={chartLabels} values={chartValues} />
      </section>

      <section className="glass-panel admin-table-section">
        <div className="admin-panel-heading">
          <div>
            <span className="pill">Content pipeline</span>
            <h2>Recent activity</h2>
          </div>
        </div>
        <div className="admin-table-wrap data-table-wrap">
          <table className="admin-data-table data-table">
            <thead>
              <tr>
                <th>Title</th>
                <th>Type</th>
                <th>Status</th>
                <th>Updated</th>
              </tr>
            </thead>
            <tbody>
              {tableRows.map((row) => (
                <tr key={`${row.type}-${row.href}`}>
                  <td>
                    <Link href={row.href}>{row.title}</Link>
                  </td>
                  <td>{row.type}</td>
                  <td>
                    <span className="status-badge" data-tone={row.status === "PUBLISHED" ? "success" : "warning"}>
                      {row.status}
                    </span>
                  </td>
                  <td className="muted">{formatDate(row.date)}</td>
                </tr>
              ))}
              {tableRows.length === 0 ? (
                <tr>
                  <td className="admin-empty-state" colSpan={4}>
                    No recent content yet.
                  </td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </div>
      </section>

      {isSuperAdmin(session) ? (
        <section className="glass-panel">
          <div className="admin-panel-heading">
            <div>
              <span className="pill">Super Admin Approval</span>
              <h2>Pending Approvals ({pendingCount})</h2>
            </div>
            <span className="status-badge">{pendingCount === 0 ? "All clear" : "Needs review"}</span>
          </div>
          <h3 style={{ margin: "1rem 0" }}>Public User Submissions</h3>
          <div className="grid-cards">
            <PendingCards gallery={userPendingGallery} posts={userPendingPosts} videos={userPendingVideos} />
          </div>
          <h3 style={{ margin: "1.5rem 0 1rem" }}>Staff Submissions</h3>
          <div className="grid-cards">
            <PendingCards gallery={staffPendingGallery} posts={staffPendingPosts} videos={staffPendingVideos} />
            {pendingCount === 0 ? <p className="admin-empty-state">No pending staff submissions right now.</p> : null}
          </div>
        </section>
      ) : null}

      {!isSuperAdmin(session) && ownRejected.length > 0 ? (
        <section className="glass-panel">
          <div className="admin-panel-heading">
            <div>
              <span className="pill">Rejected Content</span>
              <h2>Needs Update</h2>
            </div>
          </div>
          <div className="grid-cards">
            {ownRejected.map((item) => (
              <div className="card" key={`${item.type}-${item.id}`}>
                <span className="pill">{item.type}</span>
                <h3>{item.title}</h3>
                <p className="admin-error-message">{item.reason ?? "Rejected by admin."}</p>
              </div>
            ))}
          </div>
        </section>
      ) : null}

      <section className="dashboard-grid">
        <div className="glass-panel span-8">
          <div className="admin-panel-heading">
            <div>
              <span className="pill">Quick Actions</span>
              <h2>Create content</h2>
            </div>
          </div>
          <div className="cluster-row">
            <Link className="btn" href="/admin/posts/new">
              New Article
            </Link>
            <Link className="btn" href="/admin/videos/new">
              New Video
            </Link>
            <Link className="btn btn-secondary" href="/admin/pages">
              Edit Pages
            </Link>
          </div>
          <p className="muted" style={{ lineHeight: 1.7, marginTop: "1.2rem" }}>
            Publish videos, articles, homepage slider images, reviews, and page content from one place.
          </p>
        </div>
        <div className="glass-panel span-4">
          <div className="admin-panel-heading">
            <div>
              <span className="pill">Inbox</span>
              <h2>Recent messages</h2>
            </div>
          </div>
          <div className="admin-list">
          {messages.map((message) => (
            <div className="admin-list-item" key={message.id}>
              <span>
                <strong>{message.name}</strong>
                <span className="muted">{formatDate(message.createdAt)}</span>
              </span>
            </div>
          ))}
          {messages.length === 0 ? <p className="admin-empty-state">No messages yet.</p> : null}
          </div>
        </div>
      </section>

      <section className="dashboard-grid">
        <div className="glass-panel span-6">
          <div className="admin-panel-heading">
            <div>
              <span className="pill">Recent Articles</span>
              <h2>Latest Articles</h2>
            </div>
          </div>
          <div className="admin-list">
          {latestPosts.map((post) => (
            <Link className="admin-list-item" href={`/admin/posts/${post.id}`} key={post.id}>
              <span>
                <strong>{post.title}</strong>
                <span className="muted">{formatDate(post.updatedAt)}</span>
              </span>
              <span className="status-badge">{post.status}</span>
            </Link>
          ))}
          {latestPosts.length === 0 ? <p className="admin-empty-state">No articles yet.</p> : null}
          </div>
        </div>
        <div className="glass-panel span-6">
          <div className="admin-panel-heading">
            <div>
              <span className="pill">Recent Videos</span>
              <h2>Latest Videos</h2>
            </div>
          </div>
          <div className="admin-list">
          {latestVideos.map((video) => (
            <Link className="admin-list-item" href={`/admin/videos/${video.id}`} key={video.id}>
              <span>
                <strong>{video.title}</strong>
                <span className="muted">{formatDate(video.updatedAt)}</span>
              </span>
              <span className="status-badge">{video.status}</span>
            </Link>
          ))}
          {latestVideos.length === 0 ? <p className="admin-empty-state">No videos yet.</p> : null}
          </div>
        </div>
      </section>
      </>
    );
}

function DashboardMetric({ label, tone, value }: { label: string; tone: "amber" | "cyan" | "green" | "red"; value: number }) {
  return (
    <div className={`admin-kpi-card ${tone}`}>
      <div>
        <p>{label}</p>
        <strong>{value.toLocaleString()}</strong>
        <span>+12.5% vs last month</span>
      </div>
      <div className="admin-kpi-icon">{tone === "green" ? "$" : tone === "cyan" ? "↗" : tone === "amber" ? "◉" : "!"}</div>
      <svg aria-hidden="true" viewBox="0 0 220 50">
        <path d="M0 32 C24 18 38 36 60 24 C84 10 98 26 120 20 C146 14 158 36 184 22 C200 14 210 18 220 12" />
      </svg>
    </div>
  );
}

function PendingCards({
  gallery,
  posts,
  videos
}: {
  gallery: Array<{ author: { name: string | null } | null; id: string; title: string }>;
  posts: Array<{ author: { name: string | null } | null; id: string; title: string }>;
  videos: Array<{ author: { name: string | null } | null; id: string; title: string }>;
}) {
  return (
    <>
      {posts.map((post) => (
        <div className="card" key={post.id}>
          <span className="pill">Article</span>
          <h3>{post.title}</h3>
          <p className="muted">Submitted by {post.author?.name ?? "Unknown"}</p>
          <ApprovalControls id={post.id} type="post" />
        </div>
      ))}
      {videos.map((video) => (
        <div className="card" key={video.id}>
          <span className="pill">Video</span>
          <h3>{video.title}</h3>
          <p className="muted">Submitted by {video.author?.name ?? "Unknown"}</p>
          <ApprovalControls id={video.id} type="video" />
        </div>
      ))}
      {gallery.map((image) => (
        <div className="card" key={image.id}>
          <span className="pill">Gallery</span>
          <h3>{image.title}</h3>
          <p className="muted">Submitted by {image.author?.name ?? "Unknown"}</p>
          <ApprovalControls id={image.id} type="gallery" />
        </div>
      ))}
    </>
  );
}

function ApprovalControls({ id, type }: { id: string; type: "post" | "video" | "gallery" }) {
  return (
    <div style={{ display: "grid", gap: 10, marginTop: 14 }}>
      <form action={reviewContentAction}>
        <input name="id" type="hidden" value={id} />
        <input name="type" type="hidden" value={type} />
        <input name="decision" type="hidden" value="approve" />
        <button className="admin-btn admin-btn-modify" type="submit">
          Approve & publish
        </button>
      </form>
      <form action={reviewContentAction} style={{ display: "grid", gap: 8 }}>
        <input name="id" type="hidden" value={id} />
        <input name="type" type="hidden" value={type} />
        <input name="decision" type="hidden" value="reject" />
        <input className="admin-form-control" name="rejectionReason" placeholder="Reject reason shown to uploader" required />
        <button className="admin-btn admin-btn-delete" type="submit">
          Reject
        </button>
      </form>
    </div>
  );
}