import { Suspense } from "react";
import Link from "next/link";
import { fetchQuery } from "convex/nextjs";
import { api } from "../../../../../../convex/_generated/api";
import type { Id } from "../../../../../../convex/_generated/dataModel";
import { PRODUCT_DETAIL_SECTION_IDS } from "@/lib/product-detail/constants";
import { ProductDetailReviewsSkeleton } from "../state/ProductDetailReviewsSkeleton";
import { ProductDetailErrorState } from "../state/ProductDetailErrorState";
import { getProductDetailPath } from "@/lib/product-detail/constants";

const REVIEWS_INITIAL_LIMIT = 10;

function StarRating({ value }: { value: number }) {
  const full = Math.floor(value);
  return (
    <span
      className="inline-flex items-center gap-0.5"
      aria-label={`${value} out of 5 stars`}
    >
      {[1, 2, 3, 4, 5].map((star) => (
        <span
          key={star}
          className={
            star <= full ? "text-[var(--warm)]" : "text-[var(--border)]"
          }
          aria-hidden
        >
          ★
        </span>
      ))}
    </span>
  );
}

/**
 * @deprecated Use ProductDetailReviewsPanel instead for interactivity, sorting, and user submissions.
 * Reviews content — async server component that fetches and renders reviews.
 * Used as `reviewsContent` prop inside ProductDetailTabsSection.
 */
export async function ProductDetailReviewsContent({
  slug,
  category,
  subCategory,
}: {
  slug: string;
  category: string;
  subCategory: string;
}) {
  let product;
  try {
    product = await fetchQuery(api.products.getBySlug, { slug });
  } catch {
    return <ProductDetailErrorState message="Unable to load reviews." />;
  }
  if (!product) return null;

  let reviews: Awaited<
    ReturnType<typeof fetchQuery<typeof api.reviews.listByProduct>>
  >["page"];
  let total: number;
  let hasMore: boolean;
  try {
    const productId = product._id as Id<"products">;
    const result = await fetchQuery(api.reviews.listByProduct, {
      productId,
      limit: REVIEWS_INITIAL_LIMIT,
      offset: 0,
    });
    reviews = result.page;
    total = result.total;
    hasMore = result.hasMore;
  } catch {
    return <ProductDetailErrorState message="Unable to load reviews." />;
  }

  const averageRating = product.averageRating;
  const reviewCount = product.reviewCount ?? total;
  const hasReviews = reviews.length > 0;

  return (
    <div className="space-y-6">
      {/* Aggregate rating */}
      <div className="flex flex-wrap items-center gap-2 gap-y-1">
        {averageRating != null && reviewCount != null && reviewCount > 0 ? (
          <>
            <StarRating value={averageRating} />
            <span className="text-sm text-[var(--muted)]">
              {averageRating.toFixed(1)} · {reviewCount}{" "}
              {reviewCount === 1 ? "review" : "reviews"}
            </span>
          </>
        ) : hasReviews ? (
          <span className="text-sm text-[var(--muted)]">
            {total} {total === 1 ? "review" : "reviews"}
          </span>
        ) : null}
      </div>

      {!hasReviews ? (
        <div className="rounded-lg border border-[var(--separator)] bg-[var(--surface-secondary)]/50 p-6 text-center">
          <p className="text-[var(--muted)]">No reviews yet.</p>
          <Link
            href={`${getProductDetailPath(category, subCategory, slug)}#${PRODUCT_DETAIL_SECTION_IDS.reviews}`}
            className="mt-3 inline-block w-full rounded-lg bg-[var(--brand-dark)] px-4 py-2.5 text-sm font-medium text-white transition hover:opacity-90 md:w-auto"
          >
            Be the first to review
          </Link>
        </div>
      ) : (
        <ul className="m-0 list-none space-y-4 p-0">
          {reviews.map((review) => (
            <li key={review._id}>
              <article className="rounded-lg border border-[var(--separator)] bg-[var(--surface)] p-4 md:p-5">
                <h3 className="text-sm font-semibold text-[var(--foreground)] md:text-base">
                  {review.title}
                </h3>
                <div className="mt-1 flex flex-wrap items-center gap-2">
                  <StarRating value={review.rating} />
                  {review.userName && (
                    <span className="text-sm text-[var(--muted)]">
                      {review.userName}
                    </span>
                  )}
                  {review.verifiedPurchase && (
                    <span className="text-xs font-medium text-[var(--success)]">
                      Verified purchase
                    </span>
                  )}
                </div>
                <p className="mt-2 whitespace-pre-wrap text-sm text-[var(--foreground)]/80">
                  {review.content}
                </p>
                {review.helpfulCount > 0 && (
                  <p className="mt-2 text-xs text-[var(--muted)]">
                    {review.helpfulCount}{" "}
                    {review.helpfulCount === 1 ? "person" : "people"} found this
                    helpful
                  </p>
                )}
              </article>
            </li>
          ))}
        </ul>
      )}

      {hasMore && hasReviews && (
        <p className="text-sm text-[var(--muted)]">
          Showing {reviews.length} of {total} reviews.
        </p>
      )}
    </div>
  );
}

type ProductDetailReviewsSectionProps = {
  slug: string;
  category: string;
  subCategory: string;
};

/**
 * Standalone reviews section with its own Suspense boundary.
 * Used when reviews are rendered outside the tabs (backward compat).
 */
export function ProductDetailReviewsSection({
  slug,
  category,
  subCategory,
}: ProductDetailReviewsSectionProps) {
  return (
    <section
      id={PRODUCT_DETAIL_SECTION_IDS.reviews}
      aria-label="Customer reviews"
      className="scroll-mt-6"
    >
      <Suspense fallback={<ProductDetailReviewsSkeleton />}>
        <ProductDetailReviewsContent
          slug={slug}
          category={category}
          subCategory={subCategory}
        />
      </Suspense>
    </section>
  );
}
