'use client';

import React, { useState, useEffect } from 'react';
import { reviewApi } from '@/services/reviewService';
import { Star, X } from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
import { useToast } from '@/context/ToastContext';

interface WriteReviewModalProps {
  productId: number;
  productName: string;
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const WriteReviewModal: React.FC<WriteReviewModalProps> = ({
  productId,
  productName,
  isOpen,
  onClose,
  onSuccess,
}) => {
  const { user } = useAuth();
  const { showToast } = useToast();
  const [rating, setRating] = useState(0);
  const [hoverRating, setHoverRating] = useState(0);
  const [comment, setComment] = useState('');
  const [loading, setLoading] = useState(false);
  const [canReview, setCanReview] = useState(true);
  const [canReviewMessage, setCanReviewMessage] = useState('');
  const [hasPurchased, setHasPurchased] = useState(false);

  useEffect(() => {
    if (isOpen && user) {
      checkCanReview();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, user, productId]);

  const checkCanReview = async () => {
    try {
      const response = await reviewApi.canReview(productId);
      setCanReview(response.can_review);
      setCanReviewMessage(response.reason || response.message || '');
      setHasPurchased(response.has_purchased || false);
    } catch (err) {
      console.error('Error checking review status:', err);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!user) {
      showToast({ title: 'الرجاء تسجيل الدخول لكتابة مراجعة', type: 'error' });
      return;
    }

    if (rating === 0) {
      showToast({ title: 'الرجاء اختيار التقييم', type: 'error' });
      return;
    }

    if (comment.trim().length < 10) {
      showToast({ title: 'يجب أن تكون المراجعة 10 أحرف على الأقل', type: 'error' });
      return;
    }

    try {
      setLoading(true);
      await reviewApi.createReview({
        product_id: productId,
        rating,
        comment: comment.trim(),
      });

      showToast({ title: 'تم إرسال المراجعة بنجاح!', type: 'success' });
      setRating(0);
      setComment('');
      onSuccess();
      onClose();
    } catch (err) {
      console.error('Error submitting review:', err);
      const error = err as { response?: { data?: { error?: string; message?: string } } };
      const errorMessage = error?.response?.data?.error || error?.response?.data?.message || 'فشل إرسال المراجعة';
      showToast({ title: errorMessage, type: 'error' });
    } finally {
      setLoading(false);
    }
  };

  const renderStarInput = (starValue: number) => {
    const filled = starValue <= (hoverRating || rating);
    
    return (
      <button
        key={starValue}
        type="button"
        onClick={() => setRating(starValue)}
        onMouseEnter={() => setHoverRating(starValue)}
        onMouseLeave={() => setHoverRating(0)}
        className="focus:outline-none transition-transform hover:scale-110"
      >
        <Star
          className={`w-8 h-8 ${
            filled ? 'fill-yellow-400 text-yellow-400' : 'fill-gray-200 text-gray-200'
          }`}
        />
      </button>
    );
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
      <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <h2 className="text-2xl font-bold">اكتب مراجعة</h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-6">
          <div className="mb-6">
            <h3 className="font-medium text-lg mb-1">{productName}</h3>
            {hasPurchased && (
              <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-green-100 text-green-800">
                ✓ عملية شراء موثقة
              </span>
            )}
          </div>

          {!user ? (
            <div className="text-center py-8">
              <p className="text-gray-600 mb-4">الرجاء تسجيل الدخول لكتابة مراجعة</p>
              <button
                onClick={onClose}
                className="px-6 py-2 bg-[#F5411C] text-white rounded-lg hover:bg-[#e63914]"
              >
                إغلاق
              </button>
            </div>
          ) : !canReview ? (
            <div className="text-center py-8">
              <p className="text-red-600 mb-4">{canReviewMessage}</p>
              <button
                onClick={onClose}
                className="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600"
              >
                إغلاق
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit}>
              {/* Rating Input */}
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  تقييمك <span className="text-red-500">*</span>
                </label>
                <div className="flex items-center gap-1">
                  {[1, 2, 3, 4, 5].map((star) => renderStarInput(star))}
                </div>
                {rating > 0 && (
                  <p className="text-sm text-gray-600 mt-2">
                    {rating === 1 && 'ضعيف'}
                    {rating === 2 && 'مقبول'}
                    {rating === 3 && 'جيد'}
                    {rating === 4 && 'جيد جدًا'}
                    {rating === 5 && 'ممتاز'}
                  </p>
                )}
              </div>

              {/* Comment Input */}
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  مراجعتك <span className="text-red-500">*</span>
                </label>
                <textarea
                  value={comment}
                  onChange={(e) => setComment(e.target.value)}
                  placeholder="شارك تجربتك مع هذا المنتج... (10 أحرف على الأقل)"
                  rows={6}
                  maxLength={1000}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#F5411C] focus:border-transparent"
                  required
                />
                <div className="flex justify-between text-sm text-gray-500 mt-1">
                  <span>10 أحرف على الأقل</span>
                  <span>{comment.length}/1000</span>
                </div>
              </div>

              {/* Submit Button */}
              <div className="flex gap-3">
                <button
                  type="button"
                  onClick={onClose}
                  className="flex-1 px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                  disabled={loading}
                >
                  إلغاء
                </button>
                <button
                  type="submit"
                  disabled={loading || rating === 0 || comment.trim().length < 10}
                  className="flex-1 px-6 py-3 bg-[#F5411C] text-white rounded-lg hover:bg-[#e63914] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                  {loading ? 'جارٍ الإرسال...' : 'إرسال المراجعة'}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};

export default WriteReviewModal;
