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 '../../services/api/reviewService';
import useAuthStore from '../../store/useAuthStore';
import { useAuthModal } from '../../contexts/AuthModalContext';
import Recaptcha from '../common/Recaptcha';
import { recaptchaService } from '../../services/api/systemSettingsService';

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 { 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);
  const [recaptchaToken, setRecaptchaToken] = useState<string | null>(null);

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

  const rating = watch('rating');

  useEffect(() => {
    fetchReviews();
  }, [roomId]);

  const fetchReviews = async () => {
    try {
      setLoading(true);
      const response = await getRoomReviews(roomId);
      if (response.status === 'success' && response.data) {
        setReviews(response.data.reviews || []);
        setAverageRating(response.data.average_rating || 0);
        setTotalReviews(response.data.total_reviews || 0);
      }
    } 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;
    }

    
    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: any) {
      const message =
        error.response?.data?.message ||
        '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="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg border border-[#d4af37]/20 p-3 sm:p-4 backdrop-blur-xl shadow-lg shadow-[#d4af37]/5">
        <h3 className="text-sm sm:text-base font-serif font-semibold text-white 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-[#d4af37] to-[#f5d76e] bg-clip-text text-transparent">
              {averageRating > 0 
                ? averageRating.toFixed(1) 
                : 'N/A'}
            </div>
            <div className="mt-1">
              <RatingStars 
                rating={averageRating} 
                size="sm" 
              />
            </div>
            <div className="text-[10px] sm:text-xs text-gray-400 mt-1.5 font-light">
              {totalReviews} review{totalReviews !== 1 ? 's' : ''}
            </div>
          </div>
        </div>
      </div>

      {}
      {isAuthenticated ? (
        <div className="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg border border-[#d4af37]/20 p-3 sm:p-4 backdrop-blur-xl shadow-lg shadow-[#d4af37]/5">
          <h4 className="text-xs sm:text-sm font-serif font-semibold text-white mb-3 tracking-wide">
            Write Your Review
          </h4>
          <form onSubmit={handleSubmit(onSubmit)} 
            className="space-y-3"
          >
            <div>
              <label className="block text-[10px] sm:text-xs font-light 
                text-gray-300 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 
                  text-gray-300 mb-1.5 tracking-wide"
              >
                Comment
              </label>
              <textarea
                {...register('comment')}
                id="comment"
                rows={3}
                className="w-full px-2.5 py-1.5 bg-[#0a0a0a] border 
                  border-[#d4af37]/20 rounded-lg text-white placeholder-gray-500 text-xs sm:text-sm
                  focus:ring-2 focus:ring-[#d4af37]/50 
                  focus:border-[#d4af37] 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="dark"
                size="normal"
              />
            </div>

            <button
              type="submit"
              disabled={submitting}
              className="px-4 py-2 bg-gradient-to-r from-[#d4af37] to-[#c9a227] 
                text-[#0f0f0f] rounded-sm hover:from-[#f5d76e] hover:to-[#d4af37] 
                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-[#d4af37]/30 tracking-wide"
            >
              {submitting ? 'Submitting...' : 'Submit Review'}
            </button>
          </form>
        </div>
      ) : (
        <div className="bg-gradient-to-br from-[#d4af37]/10 to-[#c9a227]/5 border border-[#d4af37]/30 
          rounded-lg p-3 sm:p-4 text-center backdrop-blur-sm"
        >
          <p className="text-[#d4af37] text-xs sm:text-sm font-light">
            Please{' '}
            <button
              onClick={() => openModal('login')}
              className="font-semibold underline 
                hover:text-[#f5d76e] transition-colors"
            >
              login
            </button>{' '}
            to write a review
          </p>
        </div>
      )}

      {}
      <div>
        <h4 className="text-xs sm:text-sm font-serif font-semibold text-white mb-3 tracking-wide">
          All Reviews ({totalReviews})
        </h4>

        {loading ? (
          <div className="space-y-2.5">
            {Array.from({ length: 3 }).map((_, index) => (
              <div
                key={index}
                className="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg border border-[#d4af37]/20 p-3 
                  animate-pulse"
              >
                <div className="h-3 bg-gray-700 
                  rounded w-1/4 mb-2"
                />
                <div className="h-3 bg-gray-700 
                  rounded w-3/4"
                />
              </div>
            ))}
          </div>
        ) : reviews.length === 0 ? (
          <div className="text-center py-6 sm:py-8 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg border border-[#d4af37]/20 p-4"
          >
            <p className="text-gray-300 text-sm sm:text-base font-light">
              No reviews yet
            </p>
            <p className="text-gray-400 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="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg border border-[#d4af37]/20 
                  p-3 sm:p-4 backdrop-blur-xl shadow-sm shadow-[#d4af37]/5"
              >
                <div className="flex items-start 
                  justify-between mb-2"
                >
                  <div>
                    <h5 className="font-semibold 
                      text-white 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 
                        text-gray-400 font-light"
                      >
                        {formatDate(review.created_at)}
                      </span>
                    </div>
                  </div>
                </div>
                <p className="text-gray-300 leading-relaxed text-xs sm:text-sm font-light">
                  {review.comment}
                </p>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default ReviewSection;
