import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
import { toast } from 'react-toastify';
import RatingStars from './RatingStars';
import {
  getRoomReviews,
  createReview,
  type Review,
} from '../../reviews/services/reviewService';
import useAuthStore from '../../../store/useAuthStore';
import { useAuthModal } from '../../auth/contexts/AuthModalContext';
import Recaptcha from '../../../shared/components/Recaptcha';
import { recaptchaService } from '../../system/services/systemSettingsService';
import { useAntibotForm } from '../../auth/hooks/useAntibotForm';
import HoneypotField from '../../../shared/components/HoneypotField';
import { useTheme } from '../../../shared/contexts/ThemeContext';
import { getThemeTextClasses, getThemeCardClasses, getThemeInputClasses } from '../../../shared/utils/themeUtils';

interface ReviewSectionProps {
  roomId: number;
}

const reviewSchema = yup.object({
  rating: yup
    .number()
    .min(1, 'Please select a rating')
    .max(5)
    .required('Please provide a rating'),
  comment: yup
    .string()
    .min(10, 'Comment must be at least 10 characters')
    .max(500, 'Comment must not exceed 500 characters')
    .required('Please enter a comment'),
});

type ReviewFormData = {
  rating: number;
  comment: string;
};

const ReviewSection: React.FC<ReviewSectionProps> = ({ 
  roomId 
}) => {
  const { theme } = useTheme();
  const textClasses = getThemeTextClasses(theme.theme_layout_mode);
  const cardClasses = getThemeCardClasses(theme.theme_layout_mode);
  const inputClasses = getThemeInputClasses(theme.theme_layout_mode);
  const { isAuthenticated } = useAuthStore();
  const { openModal } = useAuthModal();
  const [reviews, setReviews] = useState<Review[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [averageRating, setAverageRating] = useState<number>(0);
  const [totalReviews, setTotalReviews] = useState<number>(0);
  
  // Enhanced antibot protection
  const {
    honeypotValue,
    setHoneypotValue,
    recaptchaToken,
    setRecaptchaToken,
    validate: validateAntibot,
    rateLimitInfo,
  } = useAntibotForm({
    formId: `review-${roomId}`,
    minTimeOnPage: 5000,
    minTimeToFill: 3000,
    requireRecaptcha: false,
    maxAttempts: 3,
    onValidationError: (errors) => {
      errors.forEach((err) => toast.error(err));
    },
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
    reset,
  } = useForm<ReviewFormData>({
    resolver: yupResolver(reviewSchema),
    defaultValues: {
      rating: 0,
      comment: '',
    },
  });

  const rating = watch('rating');

  useEffect(() => {
    fetchReviews();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [roomId]);

  const fetchReviews = async () => {
    try {
      setLoading(true);
      const response = await getRoomReviews(roomId);
      if (response.status === 'success' && response.data) {
        const reviewsList = response.data.reviews || [];
        setReviews(reviewsList);
        // Use backend values, but fallback to calculated values if backend doesn't provide them
        const backendTotal = response.data.total_reviews || 0;
        const backendAverage = response.data.average_rating || 0;
        
        // If backend doesn't provide totals but we have reviews, calculate them
        if (backendTotal === 0 && reviewsList.length > 0) {
          const calculatedTotal = reviewsList.length;
          const calculatedAverage = reviewsList.reduce((sum, r) => sum + r.rating, 0) / calculatedTotal;
          setTotalReviews(calculatedTotal);
          setAverageRating(calculatedAverage);
        } else {
          setTotalReviews(backendTotal);
          setAverageRating(backendAverage);
        }
      }
    } catch (error) {
      console.error('Error fetching reviews:', error);
      toast.error('Unable to load reviews');
    } finally {
      setLoading(false);
    }
  };

  const onSubmit = async (data: ReviewFormData) => {
    if (!isAuthenticated) {
      toast.error('Please login to review');
      return;
    }

    // Validate antibot protection
    const isValid = await validateAntibot();
    if (!isValid) {
      return;
    }
    
    if (recaptchaToken) {
      try {
        const verifyResponse = await recaptchaService.verifyRecaptcha(recaptchaToken);
        if (verifyResponse.status === 'error' || !verifyResponse.data.verified) {
          toast.error('reCAPTCHA verification failed. Please try again.');
          setRecaptchaToken(null);
          return;
        }
      } catch (error) {
        toast.error('reCAPTCHA verification failed. Please try again.');
        setRecaptchaToken(null);
        return;
      }
    }

    try {
      setSubmitting(true);
      const response = await createReview({
        room_id: roomId,
        rating: data.rating,
        comment: data.comment,
      });

      if (response.success) {
        toast.success(
          'Your review has been submitted and is pending approval'
        );
        reset();
        fetchReviews();
        setRecaptchaToken(null);
      }
    } catch (error: unknown) {
      const message =
        getUserFriendlyError(error) ||
        'Unable to submit review';
      toast.error(message);
      setRecaptchaToken(null);
    } finally {
      setSubmitting(false);
    }
  };

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

  return (
    <div className="space-y-4">
      {}
      <div className={`${cardClasses} rounded-lg border border-[var(--luxury-gold)]/20 p-3 sm:p-4 backdrop-blur-xl shadow-lg shadow-[var(--luxury-gold)]/5`}>
        <h3 className={`text-sm sm:text-base font-serif font-semibold ${textClasses.primary} mb-3 tracking-wide`}>
          Customer Reviews
        </h3>
        <div className="flex items-center gap-4">
          <div className="text-center">
            <div className="text-2xl sm:text-3xl font-serif font-bold bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-light)] bg-clip-text text-transparent">
              {totalReviews > 0 && averageRating > 0
                ? averageRating.toFixed(1) 
                : totalReviews === 0
                ? '—'
                : averageRating.toFixed(1)}
            </div>
            <div className="mt-1">
              <RatingStars 
                rating={averageRating} 
                size="sm" 
              />
            </div>
            <div className={`text-[10px] sm:text-xs ${textClasses.muted} mt-1.5 font-light`}>
              {totalReviews > 0 
                ? `${totalReviews} review${totalReviews !== 1 ? 's' : ''}`
                : 'No reviews yet'}
            </div>
          </div>
        </div>
      </div>

      {}
      {isAuthenticated ? (
        <div className={`${cardClasses} rounded-lg border border-[var(--luxury-gold)]/20 p-3 sm:p-4 backdrop-blur-xl shadow-lg shadow-[var(--luxury-gold)]/5`}>
          <h4 className={`text-xs sm:text-sm font-serif font-semibold ${textClasses.primary} mb-3 tracking-wide`}>
            Write Your Review
          </h4>
          <form onSubmit={handleSubmit(onSubmit)} 
            className="space-y-3 relative"
          >
            {/* Honeypot field - hidden from users */}
            <HoneypotField value={honeypotValue} onChange={setHoneypotValue} />
            
            {rateLimitInfo && !rateLimitInfo.allowed && (
              <div className="bg-yellow-900/50 backdrop-blur-sm border border-yellow-500/50 text-yellow-200 px-3 py-2 rounded-lg text-xs font-light mb-3">
                Too many review submissions. Please try again later.
              </div>
            )}
            <div>
              <label className={`block text-[10px] sm:text-xs font-light 
                ${textClasses.secondary} mb-1.5 tracking-wide`}
              >
                Your Rating
              </label>
              <RatingStars
                rating={rating}
                size="sm"
                interactive
                onRatingChange={(value) => 
                  setValue('rating', value)
                }
              />
              {errors.rating && (
                <p className="text-red-400 text-[10px] sm:text-xs mt-1 font-light">
                  {errors.rating.message}
                </p>
              )}
            </div>

            <div>
              <label
                htmlFor="comment"
                className={`block text-[10px] sm:text-xs font-light 
                  ${textClasses.secondary} mb-1.5 tracking-wide`}
              >
                Comment
              </label>
              <textarea
                {...register('comment')}
                id="comment"
                rows={3}
                className={`w-full px-2.5 py-1.5 ${inputClasses} border 
                  border-[var(--luxury-gold)]/20 rounded-lg placeholder-gray-500 text-xs sm:text-sm
                  focus:ring-2 focus:ring-[var(--luxury-gold)]/50 
                  focus:border-[var(--luxury-gold)] transition-all duration-300
                  font-light tracking-wide resize-none`}
                placeholder="Share your experience..."
              />
              {errors.comment && (
                <p className="text-red-400 text-[10px] sm:text-xs mt-1 font-light">
                  {errors.comment.message}
                </p>
              )}
            </div>

            {}
            <div className="flex justify-center">
              <Recaptcha
                onChange={(token) => setRecaptchaToken(token)}
                onError={(error) => {
                  console.error('reCAPTCHA error:', error);
                  setRecaptchaToken(null);
                }}
                theme={theme.theme_layout_mode === 'light' ? 'light' : 'dark'}
                size="normal"
              />
            </div>

            <button
              type="submit"
              disabled={submitting}
              className="px-4 py-2 bg-gradient-to-r from-[var(--luxury-gold)] to-[var(--luxury-gold-dark)] 
                text-[#0f0f0f] rounded-sm hover:from-[var(--luxury-gold-light)] hover:to-[var(--luxury-gold)] 
                disabled:bg-gray-800 disabled:text-gray-500 
                disabled:cursor-not-allowed 
                transition-all duration-300 font-medium text-xs sm:text-sm
                shadow-sm shadow-[var(--luxury-gold)]/30 tracking-wide"
            >
              {submitting ? 'Submitting...' : 'Submit Review'}
            </button>
          </form>
        </div>
      ) : (
        <div className="bg-gradient-to-br from-[var(--luxury-gold)]/10 to-[var(--luxury-gold-dark)]/5 border border-[var(--luxury-gold)]/30 
          rounded-lg p-3 sm:p-4 text-center backdrop-blur-sm"
        >
          <p className="text-[var(--luxury-gold)] text-xs sm:text-sm font-light">
            Please{' '}
            <button
              onClick={() => openModal('login')}
              className="font-semibold underline 
                hover:text-[var(--luxury-gold-light)] transition-colors"
            >
              login
            </button>{' '}
            to write a review
          </p>
        </div>
      )}

      {}
      <div>
        <h4 className={`text-xs sm:text-sm font-serif font-semibold ${textClasses.primary} mb-3 tracking-wide`}>
          All Reviews ({reviews.length > 0 ? reviews.length : totalReviews})
        </h4>

        {loading ? (
          <div className="space-y-2.5">
            {Array.from({ length: 3 }).map((_, index) => (
              <div
                key={index}
                className={`${cardClasses} rounded-lg border border-[var(--luxury-gold)]/20 p-3 
                  animate-pulse`}
              >
                <div className={`h-3 ${theme.theme_layout_mode === 'light' ? 'bg-gray-300' : 'bg-gray-700'} 
                  rounded w-1/4 mb-2`}
                />
                <div className={`h-3 ${theme.theme_layout_mode === 'light' ? 'bg-gray-300' : 'bg-gray-700'} 
                  rounded w-3/4`}
                />
              </div>
            ))}
          </div>
        ) : reviews.length === 0 ? (
          <div className={`text-center py-6 sm:py-8 ${cardClasses} rounded-lg border border-[var(--luxury-gold)]/20 p-4`}
          >
            <p className={`${textClasses.secondary} text-sm sm:text-base font-light`}>
              No reviews yet
            </p>
            <p className={`${textClasses.muted} text-xs sm:text-sm mt-1.5 font-light`}>
              Be the first to review this room!
            </p>
          </div>
        ) : (
          <div className="space-y-2.5 sm:space-y-3">
            {reviews.map((review) => (
              <div
                key={review.id}
                className={`${cardClasses} rounded-lg border border-[var(--luxury-gold)]/20 
                  p-3 sm:p-4 backdrop-blur-xl shadow-sm shadow-[var(--luxury-gold)]/5`}
              >
                <div className="flex items-start 
                  justify-between mb-2"
                >
                  <div>
                    <h5 className={`font-semibold 
                      ${textClasses.primary} text-xs sm:text-sm`}
                    >
                      {review.user?.full_name || 'Guest'}
                    </h5>
                    <div className="flex items-center 
                      gap-1.5 mt-1"
                    >
                      <RatingStars
                        rating={review.rating}
                        size="sm"
                      />
                      <span className={`text-[10px] sm:text-xs 
                        ${textClasses.muted} font-light`}
                      >
                        {formatDate(review.created_at)}
                      </span>
                    </div>
                  </div>
                </div>
                <p className={`${textClasses.secondary} leading-relaxed text-xs sm:text-sm font-light`}>
                  {review.comment}
                </p>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default ReviewSection;
