"use client";

import { Select, ListBox } from "@heroui/react";
import { StarRatingDisplay } from "./StarRatingDisplay";
import { ReviewSortOption } from "@/lib/product-detail/types";

type Props = {
    averageRating?: number;
    reviewCount: number;
    sortBy: ReviewSortOption;
    onSortChange: (value: ReviewSortOption) => void;
};

export function ReviewSortBar({ averageRating, reviewCount, sortBy, onSortChange }: Props) {
    const options = [
        { key: "newest", label: "Most Recent" },
        { key: "oldest", label: "Oldest First" },
        { key: "highest", label: "Highest Rated" },
        { key: "lowest", label: "Lowest Rated" },
        { key: "helpful", label: "Most Helpful" },
    ];

    return (
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
            <div className="flex flex-wrap items-center gap-2 gap-y-1">
                {averageRating != null && reviewCount > 0 ? (
                    <>
                        <StarRatingDisplay value={averageRating} />
                        <span className="text-sm font-medium text-[var(--foreground)]">
                            {averageRating.toFixed(1)} average
                        </span>
                        <span className="text-sm text-[var(--muted)]">
                            · {reviewCount} {reviewCount === 1 ? "review" : "reviews"}
                        </span>
                    </>
                ) : (
                    <span className="text-sm text-[var(--muted)]">
                        {reviewCount} {reviewCount === 1 ? "review" : "reviews"}
                    </span>
                )}
            </div>

            <div className="w-full md:w-64">
                <Select
                    aria-label="Sort reviews"
                    selectedKey={sortBy}
                    onSelectionChange={(key) => {
                        if (key) onSortChange(key as ReviewSortOption);
                    }}
                >
                    <Select.Trigger>
                        <Select.Value />
                        <Select.Indicator />
                    </Select.Trigger>
                    <Select.Popover>
                        <ListBox>
                            {options.map((opt) => (
                                <ListBox.Item key={opt.key} id={opt.key} textValue={opt.label}>
                                    {opt.label}
                                    <ListBox.ItemIndicator />
                                </ListBox.Item>
                            ))}
                        </ListBox>
                    </Select.Popover>
                </Select>
            </div>
        </div>
    );
}
