'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';

interface Review {
  id: string;
  rating: number;
  review: string;
  createdAt: string;
  project: {
    title: string;
  };
  reviewer: {
    id: string;
    name: string;
    profileImage: string;
  };
}

interface ReviewsStats {
  totalReviews: number;
  averageRating: number;
}

interface ReviewsListProps {
  freelancerId?: string;
  clientId?: string;
  showAll?: boolean;
  limit?: number;
}

export default function ReviewsList({ freelancerId, clientId, showAll = false, limit = 5 }: ReviewsListProps) {
  const [reviews, setReviews] = useState<Review[]>([]);
  const [stats, setStats] = useState<ReviewsStats>({ totalReviews: 0, averageRating: 0 });
  const [isLoading, setIsLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [hasMore, setHasMore] = useState(false);

  useEffect(() => {
    fetchReviews();
  }, [freelancerId, clientId, currentPage]);

  const fetchReviews = async () => {
    try {
      const targetId = freelancerId || clientId;
      if (!targetId) return;
      
      const queryParam = freelancerId ? `freelancerId=${freelancerId}` : `clientId=${clientId}`;
      const response = await fetch(
        `/api/reviews?${queryParam}&page=${currentPage}&limit=${limit}&request_from=public`
      );
      
      if (!response.ok) {
        throw new Error('Failed to fetch reviews');
      }

      const data = await response.json();
      
      if (currentPage === 1) {
        setReviews(data.data.reviews);
      } else {
        setReviews(prev => [...prev, ...data.data.reviews]);
      }
      
      setStats(data.data.stats);
      setTotalPages(data.data.pagination.totalPages);
      setHasMore(data.data.pagination.hasNextPage);
    } catch (error) {
    } finally {
      setIsLoading(false);
    }
  };

  const loadMore = () => {
    if (hasMore && !isLoading) {
      setCurrentPage(prev => prev + 1);
    }
  };

  const renderStars = (rating: number) => {
    return (
      <div className="star-display">
        {[1, 2, 3, 4, 5].map((star) => (
          <svg
            key={star}
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill={star <= rating ? "#FB6107" : "none"}
            stroke="#FB6107"
            strokeWidth="1"
          >
            <path d="M12 .587l3.668 7.571 8.332 1.151-6.064 5.845 1.528 8.263L12 18.896l-7.464 4.521 1.528-8.263L.001 9.309l8.332-1.151z"/>
          </svg>
        ))}
      </div>
    );
  };

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

  if (isLoading && currentPage === 1) {
    return (
      <div className="reviews-loading">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading reviews...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="reviews-list">
      {/* Reviews Summary */}
      {stats.totalReviews > 0 && (
        <div className="reviews-summary">
          <div className="rating-overview">
            <div className="avg-rating">
              <span className="rating-number">{stats.averageRating}</span>
              {renderStars(stats.averageRating)}
            </div>
            <div className="total-reviews">
              {stats.totalReviews} review{stats.totalReviews !== 1 ? 's' : ''}
            </div>
          </div>
        </div>
      )}

      {/* Reviews List */}
      <div className="reviews-container">
        {reviews.length === 0 ? (
          <div className="no-reviews">
            <p>No reviews yet</p>
          </div>
        ) : (
          <>
            {reviews.map((review) => (
              <div key={review.id} className="review-item">
                <div className="review-header">
                  <div className="reviewer-info">
                    <div className="reviewer-avatar">
                      <Image
                        src={review.reviewer.profileImage}
                        alt={review.reviewer.name}
                        width={40}
                        height={40}
                      />
                    </div>
                    <div className="reviewer-details">
                      <h6>{review.reviewer.name}</h6>
                      <div className="review-meta">
                        {renderStars(review.rating)}
                        <span className="review-date">{formatDate(review.createdAt)}</span>
                      </div>
                    </div>
                  </div>
                  <div className="project-name">
                    <span>Project: {review.project.title}</span>
                  </div>
                </div>
                <div className="review-content">
                  <p>{review.review}</p>
                </div>
              </div>
            ))}

            {/* Load More Button */}
            {showAll && hasMore && (
              <div className="load-more-container">
                <button 
                  onClick={loadMore}
                  disabled={isLoading}
                  className="load-more-btn"
                >
                  {isLoading ? 'Loading...' : 'Load More Reviews'}
                </button>
              </div>
            )}
          </>
        )}
      </div>

      <style jsx>{`
        .reviews-list {
          margin-top: 20px;
        }

        .reviews-loading {
          display: flex;
          justify-content: center;
          padding: 40px 0;
        }

        .reviews-summary {
          background: var(--color-white);
          border: 1px solid var(--border-color);
          border-radius: 10px;
          padding: 20px;
          margin-bottom: 20px;
        }

        .rating-overview {
          display: flex;
          align-items: center;
          gap: 20px;
        }

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

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

        .star-display {
          display: flex;
          gap: 2px;
        }

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

        .reviews-container {
          display: flex;
          flex-direction: column;
          gap: 15px;
        }

        .no-reviews {
          background: var(--color-white);
          border: 1px solid var(--border-color);
          border-radius: 10px;
          padding: 40px;
          text-align: center;
          color: var(--text-color);
        }

        .review-item {
          background: var(--color-white);
          border: 1px solid var(--border-color);
          border-radius: 10px;
          padding: 20px;
        }

        .review-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 15px;
          gap: 15px;
        }

        .reviewer-info {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .reviewer-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: hidden;
          flex-shrink: 0;
        }

        .reviewer-avatar img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .reviewer-details h6 {
          margin: 0 0 5px 0;
          font-size: var(--font-small);
          font-weight: 600;
          color: var(--typo-secondary);
        }

        .review-meta {
          display: flex;
          align-items: center;
          gap: 10px;
        }

        .review-date {
          font-size: var(--font-xs);
          color: var(--text-color);
        }

        .project-name {
          font-size: var(--font-xs);
          color: var(--text-color);
          font-style: italic;
        }

        .review-content p {
          margin: 0;
          line-height: 1.6;
          color: var(--text-color);
          font-size: var(--font-small);
        }

        .load-more-container {
          display: flex;
          justify-content: center;
          margin-top: 20px;
        }

        .load-more-btn {
          padding: 10px 25px;
          background-color: var(--color-primary);
          color: var(--color-white);
          border: 2px solid var(--color-primary);
          border-radius: 8px;
          font-size: var(--font-small);
          font-weight: 500;
          cursor: pointer;
          transition: all 0.3s ease;
        }

        .load-more-btn:hover:not(:disabled) {
          background-color: transparent;
          color: var(--color-primary);
        }

        .load-more-btn:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }

        @media (max-width: 768px) {
          .review-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
          }

          .rating-overview {
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
          }

          .reviewer-details h6 {
            font-size: var(--font-xs);
          }

          .review-content p {
            font-size: var(--font-xs);
          }
        }
      `}</style>
    </div>
  );
}