import { submitReview } from "@/app/product/[slug]/reviewActions";
import ReviewStarsInput from "./reviewStarsInput";
import { getCurrentUser } from "@/lib/customerAuth";

type ReviewData = {
  id: string;
  rating: number;
  title: string | null;
  body: string | null;
  isVerifiedPurchase: boolean;
  createdAt: Date;
  user: { firstName: string | null; lastName: string | null };
};

export default async function ReviewSection({
  productId,
  productSlug,
  reviews,
}: {
  productId: string;
  productSlug: string;
  reviews: ReviewData[];
}) {
  const user = await getCurrentUser();
  const reviewCount = reviews.length;
  const avgRating =
    reviewCount > 0 ? reviews.reduce((sum, r) => sum + r.rating, 0) / reviewCount : 0;

  const submitWithSlug = submitReview.bind(null, productSlug);

  return (
    <div className="mt-16 border-t border-line pt-10">
      <div className="flex items-center gap-3 mb-8">
        <h2 className="font-display font-semibold text-xl uppercase text-ink">
          Reviews
        </h2>
        {reviewCount > 0 && (
          <span className="text-sm text-ink/50">
            {avgRating.toFixed(1)} · {reviewCount} review{reviewCount !== 1 ? "s" : ""}
          </span>
        )}
      </div>

      <div className="grid lg:grid-cols-3 gap-10">
        <div className="lg:col-span-2 flex flex-col gap-6">
          {reviews.length === 0 ? (
            <p className="text-sm text-ink/50">
              No reviews yet — be the first to share your experience.
            </p>
          ) : (
            reviews.map((review) => (
              <div key={review.id} className="border-b border-line pb-5">
                <div className="flex items-center gap-2 mb-1.5">
                  <span className="text-gold font-mono text-sm">
                    {"★".repeat(review.rating)}
                    {"☆".repeat(5 - review.rating)}
                  </span>
                  {review.isVerifiedPurchase && (
                    <span className="text-[10px] font-mono uppercase bg-green-100 text-green-700 px-1.5 py-0.5 rounded">
                      Verified Purchase
                    </span>
                  )}
                </div>
                <p className="text-sm font-medium text-ink mb-1">
                  {review.user.firstName ?? "Anonymous"} {review.user.lastName?.[0] ?? ""}
                </p>
                {review.title && (
                  <p className="text-sm font-medium text-ink mb-1">{review.title}</p>
                )}
                {review.body && <p className="text-sm text-ink/70">{review.body}</p>}
                <p className="text-xs text-ink/40 font-mono mt-1.5">
                  {new Date(review.createdAt).toLocaleDateString("en-KE", {
                    day: "numeric",
                    month: "short",
                    year: "numeric",
                  })}
                </p>
              </div>
            ))
          )}
        </div>

        <div className="bg-white border border-line rounded-xl p-6 h-fit">
          <h3 className="font-display font-semibold uppercase text-sm text-ink mb-4">
            Write a Review
          </h3>

          {user ? (
            <form action={submitWithSlug} className="flex flex-col gap-3">
              <input type="hidden" name="productId" value={productId} />
              <ReviewStarsInput />
              <input
                name="title"
                placeholder="Review title (optional)"
                className="border border-line rounded-lg px-3 py-2 text-sm outline-none focus:border-harbor"
              />
              <textarea
                name="body"
                rows={4}
                placeholder="Share your thoughts about this product..."
                className="border border-line rounded-lg px-3 py-2 text-sm outline-none focus:border-harbor"
              />
              <button
                type="submit"
                className="bg-coral hover:bg-coral-dark transition-colors text-white font-semibold text-sm py-2.5 rounded-md"
              >
                Submit Review
              </button>
            </form>
          ) : (
            <p className="text-sm text-ink/60">
              <a
                href={`/account/login?callbackUrl=/product/${productSlug}`}
                className="text-harbor font-medium hover:underline"
              >
                Log in
              </a>{" "}
              to write a review.
            </p>
          )}
        </div>
      </div>
    </div>
  );
}