/**
 * CourseReviews Component
 * Displays course reviews with rating summary and individual reviews
 */

import React, { useState } from 'react';
import {
  Star,
  ThumbsUp,
  MessageSquare,
  ChevronDown,
  User,
  Filter,
} from 'lucide-react';

interface Review {
  id: string;
  userId: string;
  userName: string;
  userAvatar?: string;
  rating: number;
  title?: string;
  comment: string;
  helpful: number;
  createdAt: string;
  verified?: boolean;
}

interface RatingSummary {
  average: number;
  total: number;
  distribution: {
    5: number;
    4: number;
    3: number;
    2: number;
    1: number;
  };
}

interface CourseReviewsProps {
  courseId: string;
  reviews: Review[];
  ratingSummary: RatingSummary;
  onLoadMore?: () => void;
  onMarkHelpful?: (reviewId: string) => void;
  onReport?: (reviewId: string) => void;
  hasMore?: boolean;
  loading?: boolean;
}

const CourseReviews: React.FC<CourseReviewsProps> = ({
  courseId,
  reviews,
  ratingSummary,
  onLoadMore,
  onMarkHelpful,
  onReport,
  hasMore = false,
  loading = false,
}) => {
  const [filterRating, setFilterRating] = useState<number | null>(null);
  const [sortBy, setSortBy] = useState<'recent' | 'helpful' | 'rating'>('recent');

  const filteredReviews = reviews.filter((review) => {
    if (filterRating === null) return true;
    return review.rating === filterRating;
  });

  const sortedReviews = [...filteredReviews].sort((a, b) => {
    if (sortBy === 'helpful') return b.helpful - a.helpful;
    if (sortBy === 'rating') return b.rating - a.rating;
    return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
  });

  const renderStars = (rating: number, size: 'sm' | 'md' = 'sm') => {
    const sizeClass = size === 'sm' ? 'w-4 h-4' : 'w-5 h-5';
    return (
      <div className="flex items-center gap-0.5">
        {[1, 2, 3, 4, 5].map((star) => (
          <Star
            key={star}
            className={`${sizeClass} ${
              star <= rating
                ? 'text-yellow-400 fill-yellow-400'
                : 'text-gray-600'
            }`}
          />
        ))}
      </div>
    );
  };

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

  return (
    <div className="space-y-6">
      {/* Rating Summary */}
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
        <h3 className="text-xl font-bold text-white mb-6">Resenas del Curso</h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* Average Rating */}
          <div className="flex items-center gap-6">
            <div className="text-center">
              <div className="text-5xl font-bold text-white">
                {ratingSummary.average.toFixed(1)}
              </div>
              <div className="mt-2">{renderStars(Math.round(ratingSummary.average), 'md')}</div>
              <p className="text-sm text-gray-400 mt-1">
                {ratingSummary.total.toLocaleString()} resenas
              </p>
            </div>
          </div>

          {/* Rating Distribution */}
          <div className="space-y-2">
            {[5, 4, 3, 2, 1].map((rating) => {
              const count = ratingSummary.distribution[rating as keyof typeof ratingSummary.distribution];
              const percentage = ratingSummary.total > 0 ? (count / ratingSummary.total) * 100 : 0;

              return (
                <button
                  key={rating}
                  onClick={() => setFilterRating(filterRating === rating ? null : rating)}
                  className={`w-full flex items-center gap-3 p-1 rounded hover:bg-gray-700/50 transition-colors ${
                    filterRating === rating ? 'bg-gray-700/50' : ''
                  }`}
                >
                  <div className="flex items-center gap-1 w-20">
                    <span className="text-sm text-gray-400">{rating}</span>
                    <Star className="w-4 h-4 text-yellow-400 fill-yellow-400" />
                  </div>
                  <div className="flex-1 h-2 bg-gray-700 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-yellow-400 rounded-full transition-all"
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                  <span className="text-sm text-gray-500 w-12 text-right">
                    {count.toLocaleString()}
                  </span>
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Filter className="w-4 h-4 text-gray-400" />
          <span className="text-sm text-gray-400">
            {filteredReviews.length} resenas
            {filterRating && ` con ${filterRating} estrellas`}
          </span>
          {filterRating && (
            <button
              onClick={() => setFilterRating(null)}
              className="text-sm text-blue-400 hover:text-blue-300"
            >
              Limpiar filtro
            </button>
          )}
        </div>

        <select
          value={sortBy}
          onChange={(e) => setSortBy(e.target.value as typeof sortBy)}
          className="px-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white focus:outline-none focus:border-blue-500"
        >
          <option value="recent">Mas recientes</option>
          <option value="helpful">Mas utiles</option>
          <option value="rating">Mayor calificacion</option>
        </select>
      </div>

      {/* Reviews List */}
      <div className="space-y-4">
        {sortedReviews.length === 0 ? (
          <div className="text-center py-12 bg-gray-800 rounded-xl border border-gray-700">
            <MessageSquare className="w-12 h-12 text-gray-500 mx-auto mb-4" />
            <h4 className="font-medium text-white mb-2">Sin resenas</h4>
            <p className="text-gray-400 text-sm">
              {filterRating
                ? `No hay resenas con ${filterRating} estrellas`
                : 'Se el primero en dejar una resena'}
            </p>
          </div>
        ) : (
          sortedReviews.map((review) => (
            <ReviewCard
              key={review.id}
              review={review}
              onMarkHelpful={() => onMarkHelpful?.(review.id)}
              onReport={() => onReport?.(review.id)}
            />
          ))
        )}
      </div>

      {/* Load More */}
      {hasMore && (
        <div className="text-center">
          <button
            onClick={onLoadMore}
            disabled={loading}
            className="inline-flex items-center gap-2 px-6 py-3 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors disabled:opacity-50"
          >
            {loading ? (
              <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
            ) : (
              <ChevronDown className="w-5 h-5" />
            )}
            Cargar mas resenas
          </button>
        </div>
      )}
    </div>
  );
};

// Individual Review Card
interface ReviewCardProps {
  review: Review;
  onMarkHelpful?: () => void;
  onReport?: () => void;
}

const ReviewCard: React.FC<ReviewCardProps> = ({ review, onMarkHelpful, onReport }) => {
  const renderStars = (rating: number) => (
    <div className="flex items-center gap-0.5">
      {[1, 2, 3, 4, 5].map((star) => (
        <Star
          key={star}
          className={`w-4 h-4 ${
            star <= rating ? 'text-yellow-400 fill-yellow-400' : 'text-gray-600'
          }`}
        />
      ))}
    </div>
  );

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

  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 p-5">
      {/* Header */}
      <div className="flex items-start justify-between mb-3">
        <div className="flex items-center gap-3">
          {review.userAvatar ? (
            <img
              src={review.userAvatar}
              alt={review.userName}
              className="w-10 h-10 rounded-full object-cover"
            />
          ) : (
            <div className="w-10 h-10 rounded-full bg-gray-700 flex items-center justify-center">
              <User className="w-5 h-5 text-gray-400" />
            </div>
          )}
          <div>
            <div className="flex items-center gap-2">
              <span className="font-medium text-white">{review.userName}</span>
              {review.verified && (
                <span className="px-2 py-0.5 bg-green-500/20 text-green-400 text-xs rounded">
                  Verificado
                </span>
              )}
            </div>
            <div className="flex items-center gap-2 mt-0.5">
              {renderStars(review.rating)}
              <span className="text-xs text-gray-500">{formatDate(review.createdAt)}</span>
            </div>
          </div>
        </div>
      </div>

      {/* Title */}
      {review.title && (
        <h4 className="font-medium text-white mb-2">{review.title}</h4>
      )}

      {/* Comment */}
      <p className="text-gray-300 text-sm leading-relaxed">{review.comment}</p>

      {/* Actions */}
      <div className="flex items-center gap-4 mt-4 pt-4 border-t border-gray-700">
        <button
          onClick={onMarkHelpful}
          className="flex items-center gap-2 text-sm text-gray-400 hover:text-white transition-colors"
        >
          <ThumbsUp className="w-4 h-4" />
          <span>Util ({review.helpful})</span>
        </button>
        <button
          onClick={onReport}
          className="text-sm text-gray-500 hover:text-gray-400 transition-colors"
        >
          Reportar
        </button>
      </div>
    </div>
  );
};

export default CourseReviews;
