import Link from "next/link";
import { isUserProfileComplete, requireUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { UserShell } from "@/components/user/UserShell";

type DashboardPageProps = {
  searchParams: Promise<{ success?: string }>;
};

export default async function UserDashboardPage({ searchParams }: DashboardPageProps) {
  const [session, params] = await Promise.all([requireUser(), searchParams]);
  const [posts, videos, gallery] = await Promise.all([
    prisma.post.findMany({ where: { authorId: session.id }, orderBy: { updatedAt: "desc" }, take: 6 }),
    prisma.video.findMany({ where: { authorId: session.id }, orderBy: { updatedAt: "desc" }, take: 6 }),
    prisma.galleryImage.findMany({ where: { authorId: session.id }, orderBy: { updatedAt: "desc" }, take: 6 })
  ]);
  const submissions = [
    ...posts.map((item) => ({ id: item.id, reason: item.rejectionReason, title: item.title, type: "Blog", status: item.approvalStatus })),
    ...videos.map((item) => ({ id: item.id, reason: item.rejectionReason, title: item.title, type: "Video", status: item.approvalStatus })),
    ...gallery.map((item) => ({ id: item.id, reason: item.rejectionReason, title: item.title, type: "Gallery", status: item.approvalStatus }))
  ];
  const profileComplete = isUserProfileComplete(session);
  const approvedUploads = (session.role !== "USER" || session.isApproved) && profileComplete;

  return (
    <UserShell session={session}>
      <section className="section-head">
        <div>
          <span className="pill">User Dashboard</span>
          <h1 className="section-title">Namaste, {session.name}</h1>
          <p className="muted">Submit blogs, videos, and gallery images for admin approval.</p>
        </div>
      </section>

      {params.success === "submitted" ? (
        <p className="contact-success-message">Your content was submitted. It will be public after admin approval.</p>
      ) : null}

      {!approvedUploads ? (
        <section className="contact-form-pro">
          <span className="pill">{session.isApproved ? "Profile Required" : "Pending Approval"}</span>
          <h2>{session.isApproved ? "Complete your profile first." : "Your account is waiting for admin approval."}</h2>
          <p className="muted">
            {session.isApproved
              ? "Name, age, sex, contact, and address are mandatory before uploading content."
              : "You can login and view this dashboard, but upload access will open only after admin approves your account."}
          </p>
          {session.isApproved ? <Link className="btn" href="/dashboard/profile">Complete Profile</Link> : null}
        </section>
      ) : (
        <section className="dashboard-action-grid dashboard-action-grid--four">
          <Link className="contact-form-pro dashboard-action-card" href="/dashboard/posts/new">
            <span className="pill">Blog</span>
            <h2>Submit Blog</h2>
            <p className="muted">Write a blog for review.</p>
          </Link>
          <Link className="contact-form-pro dashboard-action-card" href="/dashboard/videos/new">
            <span className="pill">Video</span>
            <h2>Submit Video</h2>
            <p className="muted">Long-form 16:9 YouTube video.</p>
          </Link>
          <Link className="contact-form-pro dashboard-action-card dashboard-action-card--short" href="/dashboard/shorts/new">
            <span className="pill">Shorts</span>
            <h2>Upload Short</h2>
            <p className="muted">Vertical 9:16 — TikTok-style Shorts page.</p>
          </Link>
          <Link className="contact-form-pro dashboard-action-card" href="/dashboard/gallery/new">
            <span className="pill">Gallery</span>
            <h2>Upload Image</h2>
            <p className="muted">Submit gallery images for approval.</p>
          </Link>
        </section>
      )}

      <section className="contact-form-pro" style={{ marginTop: "2rem" }}>
        <span className="pill">{submissions.length} submissions</span>
        <h2>My Submissions</h2>
        <div className="admin-list">
          {submissions.map((item) => (
            <div className="admin-list-item" key={`${item.type}-${item.id}`}>
              <span>
                <strong>{item.title}</strong>
                <span className="muted">{item.type}</span>
              </span>
              <span className="status-badge">{item.status}</span>
              {item.status === "REJECTED" ? (
                <p className="admin-error-message" style={{ gridColumn: "1 / -1" }}>{item.reason ?? "Rejected by admin."}</p>
              ) : null}
            </div>
          ))}
          {submissions.length === 0 ? <p className="muted">No submissions yet.</p> : null}
        </div>
      </section>
    </UserShell>
  );
}
