/**
 * CourseReviewsSection Component
 * Combines CourseReviews display with ReviewForm
 * OQI-002: Modulo Educativo
 */

import React, { useState, useCallback } from 'react';
import { MessageSquare, Loader2 } from 'lucide-react';
import CourseReviews from './CourseReviews';
import ReviewForm from './ReviewForm';
import {
  useCourseReviews,
  useInfiniteReviews,
  useMyReview,
  useSubmitReview,
  useMarkHelpful,
  useReportReview,
} from '../hooks';
import type { RatingSummary, Review as ReviewType } from '../hooks/useCourseReviews';

interface CourseReviewsSectionProps {
  courseId: string;
  isEnrolled?: boolean;
  hasCompleted?: boolean;
}

const CourseReviewsSection: React.FC<CourseReviewsSectionProps> = ({
  courseId,
  isEnrolled = false,
  hasCompleted = false,
}) => {
  const [filterRating, setFilterRating] = useState<number | null>(null);

  // Queries
  const {
    data: reviewsData,
    isLoading: loadingReviews,
  } = useCourseReviews(courseId, filterRating ?? undefined);

  const {
    data: infiniteData,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useInfiniteReviews(courseId, 10, filterRating ?? undefined);

  const { data: myReview, isLoading: loadingMyReview } = useMyReview(courseId);

  // Mutations
  const submitReviewMutation = useSubmitReview();
  const markHelpfulMutation = useMarkHelpful();
  const reportReviewMutation = useReportReview();

  // Get all reviews from infinite query
  const allReviews: ReviewType[] = infiniteData?.pages.flatMap((page) => page.reviews) ?? [];

  // Get summary from first page
  const ratingSummary: RatingSummary = reviewsData?.summary ?? {
    average: 0,
    total: 0,
    distribution: { 5: 0, 4: 0, 3: 0, 2: 0, 1: 0 },
  };

  // Handlers
  const handleSubmitReview = useCallback(
    async (data: { rating: number; title?: string; comment: string }) => {
      await submitReviewMutation.mutateAsync({ courseId, data });
    },
    [courseId, submitReviewMutation]
  );

  const handleMarkHelpful = useCallback(
    (reviewId: string) => {
      markHelpfulMutation.mutate({ courseId, reviewId });
    },
    [courseId, markHelpfulMutation]
  );

  const handleReport = useCallback(
    (reviewId: string) => {
      // In a real app, you'd open a modal for the reason
      const reason = 'Inappropriate content';
      reportReviewMutation.mutate({ courseId, reviewId, reason });
    },
    [courseId, reportReviewMutation]
  );

  const handleLoadMore = useCallback(() => {
    if (hasNextPage && !isFetchingNextPage) {
      fetchNextPage();
    }
  }, [hasNextPage, isFetchingNextPage, fetchNextPage]);

  // Can user leave a review?
  const canReview = isEnrolled && hasCompleted && !myReview;

  if (loadingReviews && loadingMyReview) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Section Header */}
      <div className="flex items-center gap-3">
        <MessageSquare className="w-6 h-6 text-blue-400" />
        <h2 className="text-xl font-bold text-white">Resenas del Curso</h2>
      </div>

      {/* Review Form (if eligible) */}
      {canReview && (
        <ReviewForm
          courseId={courseId}
          onSubmit={handleSubmitReview}
          disabled={submitReviewMutation.isPending}
        />
      )}

      {/* Show existing user review */}
      {myReview && (
        <div className="bg-blue-500/10 border border-blue-500/30 rounded-xl p-4">
          <p className="text-sm text-blue-400 mb-2">Tu resena:</p>
          <div className="flex items-center gap-2 mb-2">
            {[1, 2, 3, 4, 5].map((star) => (
              <span
                key={star}
                className={`text-lg ${
                  star <= myReview.rating ? 'text-yellow-400' : 'text-gray-600'
                }`}
              >
                ★
              </span>
            ))}
          </div>
          {myReview.title && <p className="font-medium text-white mb-1">{myReview.title}</p>}
          <p className="text-gray-300 text-sm">{myReview.comment}</p>
        </div>
      )}

      {/* Prompt for non-enrolled users */}
      {!isEnrolled && (
        <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 text-center">
          <p className="text-gray-400">
            Inscribete y completa el curso para dejar tu resena
          </p>
        </div>
      )}

      {/* Prompt for enrolled but not completed */}
      {isEnrolled && !hasCompleted && !myReview && (
        <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 text-center">
          <p className="text-gray-400">
            Completa el curso para dejar tu resena
          </p>
        </div>
      )}

      {/* Reviews List */}
      <CourseReviews
        courseId={courseId}
        reviews={allReviews}
        ratingSummary={ratingSummary}
        onLoadMore={handleLoadMore}
        onMarkHelpful={handleMarkHelpful}
        onReport={handleReport}
        hasMore={hasNextPage ?? false}
        loading={isFetchingNextPage}
      />
    </div>
  );
};

export default CourseReviewsSection;
