'use client';

import { useState, useEffect } from 'react';
import StarRating from './StarRating';

interface ReviewStatsProps {
  userId: string;
  userType: 'freelancer' | 'client';
  className?: string;
}

interface ReviewStatsData {
  totalReviews: number;
  averageRating: number;
  ratingBreakdown: {
    1: number;
    2: number;
    3: number;
    4: number;
    5: number;
  };
}

export default function ReviewStats({ userId, userType, className = '' }: ReviewStatsProps) {
  const [stats, setStats] = useState<ReviewStatsData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetchReviewStats();
  }, [userId]);

  const fetchReviewStats = async () => {
    try {
      const response = await fetch(
        `/api/reviews?${userType === 'freelancer' ? 'freelancerId' : 'clientId'}=${userId}&limit=1000`
      );
      
      if (!response.ok) {
        throw new Error('Failed to fetch review stats');
      }

      const data = await response.json();
      
      if (data.success) {
        const reviews = data.data.reviews;
        const ratingBreakdown = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 };
        
        reviews.forEach((review: any) => {
          if (review.rating >= 1 && review.rating <= 5) {
            ratingBreakdown[review.rating as keyof typeof ratingBreakdown]++;
          }
        });

        setStats({
          totalReviews: data.data.stats.totalReviews,
          averageRating: data.data.stats.averageRating,
          ratingBreakdown
        });
      }
    } catch (error) {
      setStats({
        totalReviews: 0,
        averageRating: 0,
        ratingBreakdown: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
      });
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div className={`review-stats-loading ${className}`}>
        <div className="spinner-border spinner-border-sm" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
        <span>Loading reviews...</span>
      </div>
    );
  }

  if (!stats || stats.totalReviews === 0) {
    return (
      <div className={`no-reviews ${className}`}>
        <p>No reviews yet</p>
      </div>
    );
  }

  const getPercentage = (count: number) => {
    return stats.totalReviews > 0 ? (count / stats.totalReviews) * 100 : 0;
  };

  return (
    <div className={`review-stats ${className}`}>
      <div className="stats-summary">
        <div className="average-rating">
          <div className="rating-display">
            <span className="rating-number">{stats.averageRating}</span>
            <StarRating rating={stats.averageRating} onRatingChange={() => {}} readonly size="sm" />
          </div>
          <div className="total-reviews">
            {stats.totalReviews} review{stats.totalReviews !== 1 ? 's' : ''}
          </div>
        </div>

        <div className="rating-breakdown">
          {[5, 4, 3, 2, 1].map((rating) => (
            <div key={rating} className="rating-row">
              <span className="rating-label">{rating} star</span>
              <div className="rating-bar">
                <div 
                  className="rating-fill" 
                  style={{ width: `${getPercentage(stats.ratingBreakdown[rating as keyof typeof stats.ratingBreakdown])}%` }}
                ></div>
              </div>
              <span className="rating-count">
                {stats.ratingBreakdown[rating as keyof typeof stats.ratingBreakdown]}
              </span>
            </div>
          ))}
        </div>
      </div>

      <style jsx>{`
        .review-stats {
          background: var(--color-white);
          border: 1px solid var(--border-color);
          border-radius: 12px;
          padding: 20px;
        }

        .review-stats-loading {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 20px;
          color: var(--text-color);
          font-size: var(--font-small);
        }

        .no-reviews {
          text-align: center;
          padding: 30px 20px;
          color: var(--text-color);
        }

        .no-reviews p {
          margin: 0;
          font-style: italic;
        }

        .stats-summary {
          display: flex;
          gap: 30px;
          align-items: flex-start;
        }

        .average-rating {
          display: flex;
          flex-direction: column;
          align-items: center;
          min-width: 120px;
        }

        .rating-display {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 8px;
        }

        .rating-number {
          font-size: var(--font-24);
          font-weight: 700;
          color: var(--typo-secondary);
        }

        .total-reviews {
          font-size: var(--font-small);
          color: var(--text-color);
          text-align: center;
        }

        .rating-breakdown {
          flex: 1;
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .rating-row {
          display: flex;
          align-items: center;
          gap: 10px;
        }

        .rating-label {
          font-size: var(--font-xs);
          color: var(--text-color);
          min-width: 50px;
          text-align: right;
        }

        .rating-bar {
          flex: 1;
          height: 8px;
          background-color: var(--color-light-gray);
          border-radius: 4px;
          overflow: hidden;
        }

        .rating-fill {
          height: 100%;
          background-color: var(--color-primary);
          transition: width 0.3s ease;
        }

        .rating-count {
          font-size: var(--font-xs);
          color: var(--text-color);
          min-width: 25px;
          text-align: center;
        }

        @media (max-width: 768px) {
          .stats-summary {
            flex-direction: column;
            gap: 20px;
            align-items: stretch;
          }

          .average-rating {
            align-items: center;
            min-width: auto;
          }

          .rating-breakdown {
            align-self: stretch;
          }

          .rating-label {
            min-width: 40px;
            font-size: var(--font-xs);
          }

          .rating-count {
            min-width: 20px;
          }
        }
      `}</style>
    </div>
  );
}