"use client";

import { StarRatingDisplay } from "./star-rating-display";
import { Progress } from "@/components/ui/progress";

interface RatingSummaryProps {
  avgRating: number;
  reviewCount: number;
  reviews: { rating: number }[];
  onFilterByRating?: (rating: number | null) => void;
  selectedRating?: number | null;
}

export function RatingSummary({ 
  avgRating, 
  reviewCount, 
  reviews,
  onFilterByRating,
  selectedRating
}: RatingSummaryProps) {
  // Calculate rating distribution
  const ratingCounts = [0, 0, 0, 0, 0]; // Index 0 = 1 star, index 4 = 5 stars
  reviews.forEach(review => {
    if (review.rating >= 1 && review.rating <= 5) {
      ratingCounts[review.rating - 1]++;
    }
  });

  const ratingDistribution = ratingCounts.map(count => 
    reviewCount > 0 ? (count / reviewCount) * 100 : 0
  );

  return (
    <div className="bg-card p-6 rounded-lg border space-y-4">
      {/* Overall Rating */}
      <div className="flex items-center gap-6">
        <div className="text-center">
          <div className="text-4xl font-bold">{avgRating.toFixed(1)}</div>
          <StarRatingDisplay rating={Math.round(avgRating)} size="sm" />
          <p className="text-sm text-muted-foreground mt-1">
            {reviewCount} {reviewCount === 1 ? "review" : "reviews"}
          </p>
        </div>

        {/* Rating Breakdown */}
        <div className="flex-1 space-y-2">
          {[5, 4, 3, 2, 1].map((rating) => {
            const count = ratingCounts[rating - 1];
            const percentage = ratingDistribution[rating - 1];
            const isSelected = selectedRating === rating;

            return (
              <button
                key={rating}
                onClick={() => onFilterByRating?.(isSelected ? null : rating)}
                className={`w-full flex items-center gap-2 text-sm hover:bg-muted/50 p-1 rounded transition-colors ${
                  isSelected ? "bg-muted" : ""
                }`}
              >
                <span className="w-8 text-right">{rating}★</span>
                <Progress value={percentage} className="h-2 flex-1" />
                <span className="w-8 text-left text-muted-foreground">
                  {count}
                </span>
              </button>
            );
          })}
        </div>
      </div>

      {selectedRating && (
        <p className="text-sm text-center text-muted-foreground">
          Showing {selectedRating}-star reviews only •{" "}
          <button
            onClick={() => onFilterByRating?.(null)}
            className="text-primary hover:underline"
          >
            Clear filter
          </button>
        </p>
      )}
    </div>
  );
}
