/**
 * ReviewForm Component
 * Form for submitting course reviews with rating and comment
 * OQI-002: Modulo Educativo
 */

import React, { useState } from 'react';
import { Star, Send, Loader2, AlertCircle } from 'lucide-react';

interface ReviewFormProps {
  courseId: string;
  onSubmit: (data: { rating: number; title?: string; comment: string }) => Promise<void>;
  disabled?: boolean;
  maxCommentLength?: number;
}

const ReviewForm: React.FC<ReviewFormProps> = ({
  courseId,
  onSubmit,
  disabled = false,
  maxCommentLength = 1000,
}) => {
  const [rating, setRating] = useState(0);
  const [hoverRating, setHoverRating] = useState(0);
  const [title, setTitle] = useState('');
  const [comment, setComment] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const ratingLabels: Record<number, string> = {
    1: 'Muy malo',
    2: 'Malo',
    3: 'Regular',
    4: 'Bueno',
    5: 'Excelente',
  };

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

    if (rating === 0) {
      setError('Por favor selecciona una calificacion');
      return;
    }

    if (comment.trim().length < 10) {
      setError('El comentario debe tener al menos 10 caracteres');
      return;
    }

    setSubmitting(true);

    try {
      await onSubmit({
        rating,
        title: title.trim() || undefined,
        comment: comment.trim(),
      });
      setSuccess(true);
      setRating(0);
      setTitle('');
      setComment('');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al enviar la resena');
    } finally {
      setSubmitting(false);
    }
  };

  if (success) {
    return (
      <div className="bg-green-500/10 border border-green-500/30 rounded-xl p-6 text-center">
        <div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-green-500/20 mb-4">
          <Star className="w-6 h-6 text-green-400 fill-green-400" />
        </div>
        <h3 className="text-lg font-medium text-white mb-2">Gracias por tu resena</h3>
        <p className="text-gray-400 text-sm mb-4">
          Tu opinion ayuda a otros estudiantes a tomar mejores decisiones
        </p>
        <button
          onClick={() => setSuccess(false)}
          className="text-sm text-blue-400 hover:text-blue-300"
        >
          Escribir otra resena
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="bg-gray-800 rounded-xl border border-gray-700 p-6">
      <h3 className="text-lg font-bold text-white mb-6">Deja tu Resena</h3>

      {/* Rating Stars */}
      <div className="mb-6">
        <label className="block text-sm font-medium text-gray-400 mb-3">
          Calificacion *
        </label>
        <div className="flex items-center gap-2">
          <div className="flex items-center gap-1">
            {[1, 2, 3, 4, 5].map((star) => (
              <button
                key={star}
                type="button"
                disabled={disabled || submitting}
                onClick={() => setRating(star)}
                onMouseEnter={() => setHoverRating(star)}
                onMouseLeave={() => setHoverRating(0)}
                className="p-1 transition-transform hover:scale-110 disabled:cursor-not-allowed"
              >
                <Star
                  className={`w-8 h-8 transition-colors ${
                    star <= (hoverRating || rating)
                      ? 'text-yellow-400 fill-yellow-400'
                      : 'text-gray-600'
                  }`}
                />
              </button>
            ))}
          </div>
          {(hoverRating || rating) > 0 && (
            <span className="text-sm text-gray-400 ml-2">
              {ratingLabels[hoverRating || rating]}
            </span>
          )}
        </div>
      </div>

      {/* Title (Optional) */}
      <div className="mb-4">
        <label htmlFor="review-title" className="block text-sm font-medium text-gray-400 mb-2">
          Titulo (opcional)
        </label>
        <input
          id="review-title"
          type="text"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          disabled={disabled || submitting}
          placeholder="Resume tu experiencia en una frase"
          maxLength={100}
          className="w-full px-4 py-3 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none disabled:opacity-50"
        />
      </div>

      {/* Comment */}
      <div className="mb-4">
        <label htmlFor="review-comment" className="block text-sm font-medium text-gray-400 mb-2">
          Tu opinion *
        </label>
        <textarea
          id="review-comment"
          value={comment}
          onChange={(e) => setComment(e.target.value)}
          disabled={disabled || submitting}
          placeholder="Comparte tu experiencia con este curso. Que te gusto? Que podria mejorar?"
          maxLength={maxCommentLength}
          rows={4}
          className="w-full px-4 py-3 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none resize-none disabled:opacity-50"
        />
        <div className="flex justify-end mt-1">
          <span className={`text-xs ${comment.length > maxCommentLength * 0.9 ? 'text-yellow-400' : 'text-gray-500'}`}>
            {comment.length}/{maxCommentLength}
          </span>
        </div>
      </div>

      {/* Error Message */}
      {error && (
        <div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg mb-4">
          <AlertCircle className="w-4 h-4 text-red-400 flex-shrink-0" />
          <span className="text-sm text-red-400">{error}</span>
        </div>
      )}

      {/* Submit Button */}
      <button
        type="submit"
        disabled={disabled || submitting || rating === 0}
        className="w-full flex items-center justify-center gap-2 py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
      >
        {submitting ? (
          <>
            <Loader2 className="w-5 h-5 animate-spin" />
            Enviando...
          </>
        ) : (
          <>
            <Send className="w-5 h-5" />
            Enviar Resena
          </>
        )}
      </button>

      <p className="text-xs text-gray-500 text-center mt-4">
        Tu resena sera visible publicamente para otros estudiantes
      </p>
    </form>
  );
};

export default ReviewForm;
