import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { approveReview, rejectReview, deleteReview } from "@/lib/actions/reviews";

function Stars({ rating }: { rating: number }) {
  return <span className="text-gold-400">{"★".repeat(rating)}{"☆".repeat(5 - rating)}</span>;
}

export default async function AdminReviewsPage() {
  const reviews = await prisma.review.findMany({
    include: { product: true },
    orderBy: [{ status: "asc" }, { createdAt: "desc" }],
  });
  const pending = reviews.filter((r) => r.status === "pending");
  const decided = reviews.filter((r) => r.status !== "pending");

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Reviews</h1>
      <p className="mt-1 text-sm text-stone-500">
        Customer product reviews — tied to a verified purchase, one per customer per product. Approved reviews show on the product page.
      </p>

      {pending.length > 0 && (
        <div className="mt-6">
          <h2 className="text-sm font-semibold text-amber-800">Awaiting moderation ({pending.length})</h2>
          <div className="mt-2 space-y-3">
            {pending.map((r) => (
              <div key={r.id} className="rounded-lg border border-amber-200 bg-amber-50/50 p-4">
                <div className="flex items-start justify-between">
                  <div>
                    <Link href={`/product/${r.product.slug}`} className="text-sm font-medium text-rose-700 hover:underline">
                      {r.product.name}
                    </Link>
                    <p className="text-xs text-stone-500">
                      {r.customerName} · {formatDate(r.createdAt)}
                    </p>
                  </div>
                  <Stars rating={r.rating} />
                </div>
                {r.title && <p className="mt-2 text-sm font-medium text-stone-800">{r.title}</p>}
                <p className="mt-1 text-sm text-stone-600">{r.body}</p>
                <div className="mt-3 flex gap-3">
                  <form action={approveReview.bind(null, r.id)}>
                    <button type="submit" className="rounded-md bg-emerald-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-emerald-800">
                      Approve
                    </button>
                  </form>
                  <form action={rejectReview.bind(null, r.id)}>
                    <button type="submit" className="rounded-md border border-stone-300 px-3 py-1.5 text-xs font-medium text-stone-600 hover:bg-stone-50">
                      Reject
                    </button>
                  </form>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {decided.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No moderated reviews yet.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Product</th>
                <th className="p-3">Customer</th>
                <th className="p-3">Rating</th>
                <th className="p-3">Review</th>
                <th className="p-3">Status</th>
                <th className="p-3">Date</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {decided.map((r) => (
                <tr key={r.id}>
                  <td className="whitespace-nowrap p-3">
                    <Link href={`/product/${r.product.slug}`} className="font-medium text-rose-700 hover:underline">
                      {r.product.name}
                    </Link>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.customerName}</td>
                  <td className="whitespace-nowrap p-3">
                    <Stars rating={r.rating} />
                  </td>
                  <td className="max-w-xs p-3 text-stone-600">
                    {r.title && <span className="font-medium">{r.title}: </span>}
                    {r.body}
                  </td>
                  <td className="whitespace-nowrap p-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${r.status === "approved" ? "bg-emerald-100 text-emerald-800" : "bg-stone-200 text-stone-600"}`}>
                      {r.status}
                    </span>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(r.createdAt)}</td>
                  <td className="whitespace-nowrap p-3 text-right">
                    <div className="flex items-center justify-end gap-2">
                      {r.status === "rejected" && (
                        <form action={approveReview.bind(null, r.id)}>
                          <button type="submit" className="text-xs text-emerald-700 hover:underline">
                            Approve
                          </button>
                        </form>
                      )}
                      {r.status === "approved" && (
                        <form action={rejectReview.bind(null, r.id)}>
                          <button type="submit" className="text-xs text-stone-500 hover:text-amber-700">
                            Unapprove
                          </button>
                        </form>
                      )}
                      <form action={deleteReview.bind(null, r.id)}>
                        <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                          Delete
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
