"use client";

import { useState } from "react";
import { useQuery } from "convex/react";
import { api } from "../../../../../../convex/_generated/api";
import type { Id } from "../../../../../../convex/_generated/dataModel";
import type { ProductDetailReview, ReviewSortOption } from "@/lib/product-detail/types";
import { ReviewSortBar } from "./ReviewSortBar";
import { ReviewList } from "./ReviewList";
import { ReviewForm } from "./ReviewForm";
import { ProductDetailErrorState } from "../state/ProductDetailErrorState";
import { ProductDetailReviewsSkeleton } from "../state/ProductDetailReviewsSkeleton";

type Props = {
    productId: string;
    initialRating?: number;
    initialReviewCount?: number;
};

const LIMIT = 10;

export function ProductDetailReviewsPanel({ productId, initialRating, initialReviewCount }: Props) {
    const [sortBy, setSortBy] = useState<ReviewSortOption>("newest");
    const [offset, setOffset] = useState(0);

    const result = useQuery(api.reviews.listByProductSorted, {
        productId: productId as Id<"products">,
        sortBy,
        limit: offset + LIMIT,
        offset: 0,
    });

    if (result === undefined) return <ProductDetailReviewsSkeleton />;
    if (result === null) return <ProductDetailErrorState message="Could not load reviews" />;

    const { page, total, hasMore } = result;

    const handleLoadMore = () => {
        setOffset((prev) => prev + LIMIT);
    };

    const handleSortChange = (newSort: ReviewSortOption) => {
        setSortBy(newSort);
        setOffset(0);
    };

    const actualReviewCount = initialReviewCount ?? total;
    const hasEverHadReviews = actualReviewCount > 0 || total > 0;

    return (
        <div className="flex flex-col">
            {hasEverHadReviews ? (
                <>
                    <ReviewSortBar
                        averageRating={initialRating}
                        reviewCount={actualReviewCount}
                        sortBy={sortBy}
                        onSortChange={handleSortChange}
                    />
                    <ReviewList
                        reviews={page as ProductDetailReview[]}
                        total={total}
                        hasMore={hasMore}
                        isLoading={result === undefined}
                        onLoadMore={handleLoadMore}
                    />
                </>
            ) : (
                <div className="rounded-lg border border-[var(--separator)] bg-[var(--surface-secondary)]/50 p-6 text-center">
                    <p className="text-[var(--muted)] mb-2">No reviews yet.</p>
                    <p className="text-sm text-[var(--muted)]">Be the first to share your experience!</p>
                </div>
            )}

            <ReviewForm productId={productId as Id<"products">} />
        </div>
    );
}
