
'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Star, ThumbsUp, MessageSquare, Clock } from 'lucide-react';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';

interface Review {
  id: string;
  contractorId: string;
  customerId: string;
  overallRating: number;
  qualityRating?: number;
  timelinessRating?: number;
  communicationRating?: number;
  valueRating?: number;
  title?: string;
  comment: string;
  isVerified: boolean;
  verifiedPurchase: boolean;
  contractorResponse?: string;
  respondedAt?: string;
  helpfulCount: number;
  isFeatured: boolean;
  createdAt: string;
}

interface ReviewStats {
  averageRating: number;
  totalReviews: number;
  ratingDistribution: Record<number, number>;
}

interface ReviewListProps {
  contractorId: string;
  limit?: number;
  showStats?: boolean;
}

export function ReviewList({ contractorId, limit = 10, showStats = true }: ReviewListProps) {
  const [reviews, setReviews] = useState<Review[]>([]);
  const [stats, setStats] = useState<ReviewStats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchReviews();
  }, [contractorId]);

  const fetchReviews = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        `/api/reviews?contractorId=${contractorId}&published=true&limit=${limit}`
      );
      if (response.ok) {
        const data = await response.json();
        setReviews(data.reviews);
        if (data.stats) setStats(data.stats);
      }
    } catch (error) {
      console.error('Error fetching reviews:', error);
    } finally {
      setLoading(false);
    }
  };

  const renderStars = (rating: number) => {
    return (
      <div className="flex gap-1">
        {[1, 2, 3, 4, 5].map((star) => (
          <Star
            key={star}
            className={`w-4 h-4 ${
              star <= rating
                ? 'text-amber-500 fill-amber-500'
                : 'text-gray-300'
            }`}
          />
        ))}
      </div>
    );
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  };

  if (loading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3].map((i) => (
          <Card key={i} className="animate-pulse">
            <CardContent className="p-6">
              <div className="h-32 bg-muted rounded" />
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats Section */}
      {showStats && stats && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <div className="flex items-center gap-3">
                  <span className="text-5xl font-bold">{stats.averageRating.toFixed(1)}</span>
                  <div>
                    {renderStars(stats.averageRating)}
                    <p className="text-sm text-muted-foreground mt-1">
                      Based on {stats.totalReviews} reviews
                    </p>
                  </div>
                </div>
              </div>

              {/* Rating Distribution */}
              <div className="space-y-2">
                {[5, 4, 3, 2, 1].map((rating) => {
                  const count = stats.ratingDistribution[rating] || 0;
                  const percentage = stats.totalReviews > 0
                    ? (count / stats.totalReviews) * 100
                    : 0;
                  return (
                    <div key={rating} className="flex items-center gap-2">
                      <span className="text-sm w-8">{rating} ★</span>
                      <div className="w-32 h-2 bg-gray-200 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-amber-500"
                          style={{ width: `${percentage}%` }}
                        />
                      </div>
                      <span className="text-sm text-muted-foreground w-12">
                        {count}
                      </span>
                    </div>
                  );
                })}
              </div>
            </div>
          </CardHeader>
        </Card>
      )}

      {/* Reviews List */}
      <div className="space-y-4">
        {reviews.length === 0 ? (
          <Card>
            <CardContent className="p-12 text-center">
              <MessageSquare className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
              <p className="text-muted-foreground">No reviews yet</p>
            </CardContent>
          </Card>
        ) : (
          reviews.map((review, index) => (
            <motion.div
              key={review.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.1 }}
            >
              <Card className={review.isFeatured ? 'border-amber-500 border-2' : ''}>
                <CardContent className="p-6">
                  {/* Review Header */}
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-center gap-3">
                      <Avatar>
                        <AvatarFallback>
                          {review.customerId.slice(0, 2).toUpperCase()}
                        </AvatarFallback>
                      </Avatar>
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="font-semibold">Anonymous Customer</span>
                          {review.isVerified && (
                            <Badge variant="secondary" className="text-xs">
                              Verified
                            </Badge>
                          )}
                          {review.isFeatured && (
                            <Badge variant="default" className="text-xs bg-amber-500">
                              Featured
                            </Badge>
                          )}
                        </div>
                        <div className="flex items-center gap-2 mt-1">
                          {renderStars(review.overallRating)}
                          <span className="text-sm text-muted-foreground">
                            <Clock className="w-3 h-3 inline mr-1" />
                            {formatDate(review.createdAt)}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Review Content */}
                  {review.title && (
                    <h4 className="font-semibold mb-2">{review.title}</h4>
                  )}
                  <p className="text-muted-foreground mb-4 leading-relaxed">
                    {review.comment}
                  </p>

                  {/* Detailed Ratings */}
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                    {review.qualityRating && (
                      <div className="text-sm">
                        <p className="text-muted-foreground">Quality</p>
                        <div className="flex items-center gap-1">
                          {renderStars(review.qualityRating)}
                        </div>
                      </div>
                    )}
                    {review.timelinessRating && (
                      <div className="text-sm">
                        <p className="text-muted-foreground">Timeliness</p>
                        <div className="flex items-center gap-1">
                          {renderStars(review.timelinessRating)}
                        </div>
                      </div>
                    )}
                    {review.communicationRating && (
                      <div className="text-sm">
                        <p className="text-muted-foreground">Communication</p>
                        <div className="flex items-center gap-1">
                          {renderStars(review.communicationRating)}
                        </div>
                      </div>
                    )}
                    {review.valueRating && (
                      <div className="text-sm">
                        <p className="text-muted-foreground">Value</p>
                        <div className="flex items-center gap-1">
                          {renderStars(review.valueRating)}
                        </div>
                      </div>
                    )}
                  </div>

                  {/* Contractor Response */}
                  {review.contractorResponse && (
                    <>
                      <Separator className="my-4" />
                      <div className="bg-muted/50 p-4 rounded-lg">
                        <div className="flex items-center gap-2 mb-2">
                          <Badge variant="outline">Contractor Response</Badge>
                          <span className="text-xs text-muted-foreground">
                            {review.respondedAt && formatDate(review.respondedAt)}
                          </span>
                        </div>
                        <p className="text-sm">{review.contractorResponse}</p>
                      </div>
                    </>
                  )}

                  {/* Helpful Button */}
                  <div className="flex items-center gap-4 mt-4">
                    <Button variant="ghost" size="sm">
                      <ThumbsUp className="w-4 h-4 mr-2" />
                      Helpful ({review.helpfulCount})
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          ))
        )}
      </div>
    </div>
  );
}
