import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import { getCurrentCustomerId } from "@/lib/customer-auth";
import { submitReview, deleteOwnReview } from "@/lib/actions/customer-account";

function Stars({ rating, size = "text-sm" }: { rating: number; size?: string }) {
  return <span className={`text-gold-400 ${size}`}>{"★".repeat(rating)}{"☆".repeat(5 - rating)}</span>;
}

const PURCHASE_STATUSES = ["paid", "shipped", "delivered"];

export default async function ProductReviews({ productId, productSlug, error }: { productId: string; productSlug: string; error?: string }) {
  const customerId = await getCurrentCustomerId();

  const [approved, myReview, purchased] = await Promise.all([
    prisma.review.findMany({ where: { productId, status: "approved" }, orderBy: { createdAt: "desc" } }),
    customerId ? prisma.review.findUnique({ where: { productId_customerId: { productId, customerId } } }) : null,
    customerId ? prisma.orderItem.findFirst({ where: { productId, order: { customerId, status: { in: PURCHASE_STATUSES } } } }) : null,
  ]);

  const avg = approved.length > 0 ? approved.reduce((s, r) => s + r.rating, 0) / approved.length : 0;

  return (
    <section className="mt-16 max-w-3xl">
      <div className="flex items-center gap-3">
        <h2 className="font-[family-name:var(--font-heading)] text-xl font-semibold text-stone-800">Reviews</h2>
        {approved.length > 0 && (
          <span className="flex items-center gap-1 text-sm text-stone-500">
            <Stars rating={Math.round(avg)} /> {avg.toFixed(1)} ({approved.length})
          </span>
        )}
      </div>

      {error && <p className="mt-3 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <div className="mt-4 space-y-4">
        {approved.length === 0 ? (
          <p className="text-sm text-stone-500">No reviews yet.</p>
        ) : (
          approved.map((r) => (
            <div key={r.id} className="rounded-lg border border-rose-100 bg-white p-4">
              <div className="flex items-center justify-between">
                <Stars rating={r.rating} />
                <span className="text-xs text-stone-400">{formatDate(r.createdAt)}</span>
              </div>
              {r.title && <p className="mt-1 text-sm font-medium text-stone-800">{r.title}</p>}
              <p className="mt-1 text-sm text-stone-600">{r.body}</p>
              <p className="mt-1 text-xs text-stone-400">{r.customerName}</p>
            </div>
          ))
        )}
      </div>

      <div className="mt-6 rounded-lg border border-rose-100 bg-white p-4">
        {!customerId ? (
          <p className="text-sm text-stone-500">
            <Link href="/account/login" className="text-rose-700 hover:underline">
              Sign in
            </Link>{" "}
            after your order arrives to leave a review.
          </p>
        ) : !purchased ? (
          <p className="text-sm text-stone-500">You can review this product once your order for it has been paid.</p>
        ) : (
          <>
            <h3 className="text-sm font-semibold text-stone-700">{myReview ? "Edit your review" : "Write a review"}</h3>
            {myReview?.status === "pending" && <p className="mt-1 text-xs text-amber-700">Your review is awaiting moderation.</p>}
            {myReview?.status === "rejected" && <p className="mt-1 text-xs text-stone-500">Your review wasn&apos;t published — you can edit and resubmit it.</p>}
            <form action={submitReview.bind(null, productId)} className="mt-2 space-y-2">
              <select name="rating" defaultValue={myReview?.rating ?? ""} required className="rounded-md border border-stone-300 px-2 py-1.5 text-sm">
                <option value="">Rating…</option>
                {[5, 4, 3, 2, 1].map((n) => (
                  <option key={n} value={n}>
                    {n} star{n > 1 ? "s" : ""}
                  </option>
                ))}
              </select>
              <input name="title" defaultValue={myReview?.title ?? ""} maxLength={100} placeholder="Title (optional)" className="block w-full rounded-md border border-stone-300 px-2 py-1.5 text-sm" />
              <textarea name="body" defaultValue={myReview?.body ?? ""} required maxLength={2000} rows={3} placeholder="Share your experience" className="block w-full rounded-md border border-stone-300 px-2 py-1.5 text-sm" />
              <button type="submit" className="rounded-md bg-rose-700 px-4 py-1.5 text-sm font-semibold text-white hover:bg-rose-800">
                {myReview ? "Update review" : "Submit review"}
              </button>
            </form>
            {myReview && (
              <form action={deleteOwnReview.bind(null, myReview.id, productSlug)} className="mt-2">
                <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                  Delete review
                </button>
              </form>
            )}
          </>
        )}
      </div>
    </section>
  );
}
