import { useEffect, useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Star } from 'lucide-react';

interface RatingDistributionProps {
  rideId: string;
  totalReviews: number;
  averageRating: number;
}

interface RatingCount {
  rating: number;
  count: number;
}

export function RatingDistribution({ rideId, totalReviews, averageRating }: RatingDistributionProps) {
  const [distribution, setDistribution] = useState<RatingCount[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchDistribution() {
      const { data, error } = await supabase
        .from('reviews')
        .select('rating')
        .eq('ride_id', rideId)
        .eq('moderation_status', 'approved');

      if (!error && data) {
        const counts = [5, 4, 3, 2, 1].map(rating => ({
          rating,
          count: data.filter(r => r.rating === rating).length
        }));
        setDistribution(counts);
      }
      setLoading(false);
    }

    fetchDistribution();
  }, [rideId]);

  if (loading) {
    return null;
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Rating Breakdown</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="text-center pb-4 border-b border-border">
          <div className="flex items-center justify-center gap-2 mb-2">
            <Star className="w-8 h-8 fill-yellow-400 text-yellow-400" />
            <span className="text-4xl font-bold">{averageRating.toFixed(1)}</span>
          </div>
          <div className="text-sm text-muted-foreground">
            Based on {totalReviews} {totalReviews === 1 ? 'review' : 'reviews'}
          </div>
        </div>

        <div className="space-y-3">
          {distribution.map(({ rating, count }) => {
            const percentage = totalReviews > 0 ? (count / totalReviews) * 100 : 0;
            return (
              <div key={rating} className="flex items-center gap-3">
                <div className="flex items-center gap-1 w-16">
                  <span className="text-sm font-medium">{rating}</span>
                  <Star className="w-3 h-3 fill-yellow-400 text-yellow-400" />
                </div>
                <Progress value={percentage} className="flex-1 h-2" />
                <span className="text-sm text-muted-foreground w-12 text-right">
                  {count}
                </span>
              </div>
            );
          })}
        </div>
      </CardContent>
    </Card>
  );
}
