import React, { useState, useEffect } from 'react';

const FeedbackWeighting = ({ onComplete, onCancel }) => {
  const [feedbackWords, setFeedbackWords] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const [weights, setWeights] = useState({});

  useEffect(() => {
    fetchQueuedFeedbackWords();
  }, []);

  const fetchQueuedFeedbackWords = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await fetch('/api/v1/feedback/queued');
      if (response.ok) {
        const data = await response.json();
        const words = data.queued_words || [];
        setFeedbackWords(words);

        // Initialize weights state
        const initialWeights = {};
        words.forEach(word => {
          initialWeights[word.word] = word.weight;
        });
        setWeights(initialWeights);
      } else {
        throw new Error(`Failed to fetch feedback words: ${response.status}`);
      }
    } catch (err) {
      console.error('Error fetching feedback words:', err);
      setError('Failed to load feedback words. Please try again.');

      // Fallback to mock data for development
      const mockWords = [
        { key: 'feedback00', word: 'labyrinth', weight: 3 },
        { key: 'feedback01', word: 'residue', weight: 3 },
        { key: 'feedback02', word: 'tremor', weight: 3 },
        { key: 'feedback03', word: 'effigy', weight: 3 },
        { key: 'feedback04', word: 'quasar', weight: 3 },
        { key: 'feedback05', word: 'gossamer', weight: 3 }
      ];
      setFeedbackWords(mockWords);

      const initialWeights = {};
      mockWords.forEach(word => {
        initialWeights[word.word] = word.weight;
      });
      setWeights(initialWeights);
    } finally {
      setLoading(false);
    }
  };

  const handleWeightChange = (word, newWeight) => {
    setWeights(prev => ({
      ...prev,
      [word]: newWeight
    }));
  };

  const handleSubmit = async () => {
    setSubmitting(true);
    setError(null);

    try {
      const response = await fetch('/api/v1/feedback/rate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ ratings: weights })
      });

      if (response.ok) {
        const data = await response.json();
        console.log('Feedback words rated successfully:', data);

        // Call onComplete callback if provided
        if (onComplete) {
          onComplete(data);
        }
      } else {
        const errorData = await response.json();
        throw new Error(errorData.detail || `Failed to rate feedback words: ${response.status}`);
      }
    } catch (err) {
      console.error('Error rating feedback words:', err);
      setError(`Failed to submit ratings: ${err.message}`);
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <div className="flex items-center justify-center py-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
          <span className="ml-3 text-gray-600">Loading feedback words...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg shadow-md p-6 mb-6">
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-xl font-bold text-gray-800">
          Rate Feedback Words
        </h2>
        <button
          onClick={onCancel}
          className="text-gray-500 hover:text-gray-700"
          title="Cancel"
        >
          <i className="fas fa-times text-xl"></i>
        </button>
      </div>

      {error && (
        <div className="bg-red-50 border-l-4 border-red-400 p-4 mb-6">
          <div className="flex">
            <div className="flex-shrink-0">
              <i className="fas fa-exclamation-circle text-red-400"></i>
            </div>
            <div className="ml-3">
              <p className="text-sm text-red-700">{error}</p>
            </div>
          </div>
        </div>
      )}

      <div className="space-y-4">
        {feedbackWords.map((item, index) => (
          <div key={item.key} className="border border-gray-200 rounded-lg p-4">
            <div className="mb-3">
              <h3 className="text-lg font-semibold text-gray-800 mb-2">
                {item.word}
              </h3>
              <div className="relative">
                <input
                  type="range"
                  min="0"
                  max="6"
                  value={weights[item.word] || 3}
                  onChange={(e) => handleWeightChange(item.word, parseInt(e.target.value))}
                  className="w-full h-8 bg-gray-200 rounded-lg appearance-none cursor-pointer slider-thumb-hidden"
                  style={{
                    background: `linear-gradient(to right, #ef4444 0%, #f97316 16.67%, #eab308 33.33%, #22c55e 50%, #3b82f6 66.67%, #8b5cf6 83.33%, #a855f7 100%)`
                  }}
                />
             </div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-8 pt-6 border-t border-gray-200">
        <div className="flex justify-end space-x-3">
          <button
            onClick={onCancel}
            className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"
            disabled={submitting}
          >
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={submitting}
            className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {submitting ? (
              <>
                <i className="fas fa-spinner fa-spin mr-2"></i>
                Submitting...
              </>
            ) : (
              <>
                <i className="fas fa-check mr-2"></i>
                Submit
              </>
            )}
          </button>
        </div>
      </div>

      <style jsx>{`
        .slider-thumb-hidden::-webkit-slider-thumb {
          -webkit-appearance: none;
          appearance: none;
          width: 24px;
          height: 24px;
          background: #3b82f6;
          border-radius: 50%;
          cursor: pointer;
          border: 2px solid white;
          box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }

        .slider-thumb-hidden::-moz-range-thumb {
          width: 24px;
          height: 24px;
          background: #3b82f6;
          border-radius: 50%;
          cursor: pointer;
          border: 2px solid white;
          box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
      `}</style>
    </div>
  );
};

export default FeedbackWeighting;

