import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { ReviewDeleteButton } from "./ReviewDeleteButton";

export default async function AdminReviewsPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  const params = await searchParams;
  const page = Math.max(1, parseInt(String(params.page ?? "1")));
  const perPage = 50;

  const where = {
    user: { is: {} },
  };

  const [reviews, total] = await Promise.all([
    prisma.review.findMany({
      where,
      orderBy: { created_at: "desc" },
      skip: (page - 1) * perPage,
      take: perPage,
      include: {
        user: { select: { id: true, username: true } },
      },
    }),
    prisma.review.count({ where }),
  ]);

  const totalPages = Math.ceil(total / perPage);

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Review Moderation</h1>

      <p className="text-text-muted text-sm">
        {total.toLocaleString()} reviews total
      </p>

      <div className="bg-surface rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="border-b border-surface-light text-text-muted text-sm">
                <th className="p-4 font-medium">ID</th>
                <th className="p-4 font-medium">Author</th>
                <th className="p-4 font-medium">For User</th>
                <th className="p-4 font-medium">Stars</th>
                <th className="p-4 font-medium">Review</th>
                <th className="p-4 font-medium">Date</th>
                <th className="p-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {reviews.map((review) => (
                <tr
                  key={review.id}
                  className="border-b border-surface-light last:border-0 hover:bg-surface-light/50"
                >
                  <td className="p-4 text-text-muted font-mono text-sm">
                    {review.id}
                  </td>
                  <td className="p-4 font-medium">
                    {review.author || "-"}
                  </td>
                  <td className="p-4 text-text-muted">
                    {review.user?.username || "-"}
                  </td>
                  <td className="p-4">
                    {review.stars != null ? (
                      <span className="text-yellow-400">
                        {"*".repeat(review.stars)}
                      </span>
                    ) : (
                      "-"
                    )}
                  </td>
                  <td className="p-4 text-text-muted text-sm max-w-[300px] truncate">
                    {review.review_text || "-"}
                  </td>
                  <td className="p-4 text-text-muted text-sm">
                    {review.date
                      ? new Date(review.date).toLocaleDateString()
                      : new Date(review.created_at).toLocaleDateString()}
                  </td>
                  <td className="p-4">
                    <ReviewDeleteButton reviewId={review.id} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2">
          {page > 1 && (
            <a
              href={`/admin/reviews?page=${page - 1}`}
              className="bg-surface hover:bg-surface-light text-text-muted px-3 py-1.5 rounded transition-colors text-sm"
            >
              Previous
            </a>
          )}
          <span className="text-text-muted text-sm">
            Page {page} of {totalPages}
          </span>
          {page < totalPages && (
            <a
              href={`/admin/reviews?page=${page + 1}`}
              className="bg-surface hover:bg-surface-light text-text-muted px-3 py-1.5 rounded transition-colors text-sm"
            >
              Next
            </a>
          )}
        </div>
      )}
    </div>
  );
}
