import React, { useState, useRef, useEffect } from 'react';
import { useExam } from '../../contexts/ExamContext';
import { InteractiveQuestion } from '../../types';
import { cn } from '../../utils/cn';
import { 
  Image, 
  Play, 
  Pause, 
  Volume2, 
  VolumeX,
  Move,
  Check,
  X,
  RotateCcw,
  Lightbulb,
  HelpCircle,
  Star
} from 'lucide-react';

interface EnhancedMCQComponentProps {
  question: InteractiveQuestion;
  questionIndex: number;
  onAnswerChange: (answer: any) => void;
  adminLanguage: string;
}

interface DragDropState {
  draggedItem: string | null;
  dropZones: { [key: string]: string | null };
  isComplete: boolean;
}

const EnhancedMCQComponent: React.FC<EnhancedMCQComponentProps> = ({
  question,
  questionIndex,
  onAnswerChange,
  adminLanguage
}) => {
  const { state, setDragDropState } = useExam();
  const [selectedAnswers, setSelectedAnswers] = useState<number[]>([]);
  const [dragDropState, setLocalDragDropState] = useState<DragDropState>({
    draggedItem: null,
    dropZones: {},
    isComplete: false
  });
  const [showHint, setShowHint] = useState(false);
  const [showConfidence, setShowConfidence] = useState(false);
  const [confidence, setConfidence] = useState(0);
  const [mediaStates, setMediaStates] = useState<{[key: string]: any}>({});
  const audioRefs = useRef<{[key: string]: HTMLAudioElement}>({});

  // Initialize dari state yang tersimpan
  useEffect(() => {
    const savedAnswer = state.answers[questionIndex];
    if (savedAnswer) {
      if (question.type === 'drag_drop') {
        setLocalDragDropState(savedAnswer);
      } else {
        setSelectedAnswers(Array.isArray(savedAnswer) ? savedAnswer : [savedAnswer]);
      }
    }
  }, [questionIndex, state.answers, question.type]);

  // Handle answer selection
  const handleAnswerSelect = (optionIndex: number) => {
    let newSelection: number[];
    
    if (question.content?.multipleAnswers) {
      if (selectedAnswers.includes(optionIndex)) {
        newSelection = selectedAnswers.filter(id => id !== optionIndex);
      } else {
        newSelection = [...selectedAnswers, optionIndex];
      }
    } else {
      newSelection = [optionIndex];
    }
    
    setSelectedAnswers(newSelection);
    onAnswerChange(question.content?.multipleAnswers ? newSelection : newSelection[0]);
  };

  // Handle drag start
  const handleDragStart = (e: React.DragEvent, itemId: string) => {
    e.dataTransfer.setData('text/plain', itemId);
    setLocalDragDropState(prev => ({ ...prev, draggedItem: itemId }));
  };

  // Handle drag over
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  // Handle drop
  const handleDrop = (e: React.DragEvent, zoneId: string) => {
    e.preventDefault();
    const itemId = e.dataTransfer.getData('text/plain');
    
    const newDropZones = { ...dragDropState.dropZones };
    
    // Remove item from previous zone
    Object.keys(newDropZones).forEach(zone => {
      if (newDropZones[zone] === itemId) {
        newDropZones[zone] = null;
      }
    });
    
    // Add to new zone
    newDropZones[zoneId] = itemId;
    
    const newState = {
      ...dragDropState,
      dropZones: newDropZones,
      draggedItem: null,
      isComplete: Object.values(newDropZones).filter(Boolean).length === question.content?.dragDropItems?.length
    };
    
    setLocalDragDropState(newState);
    setDragDropState(questionIndex.toString(), newState);
    onAnswerChange(newState);
  };

  // Reset drag drop
  const resetDragDrop = () => {
    const resetState = {
      draggedItem: null,
      dropZones: {},
      isComplete: false
    };
    setLocalDragDropState(resetState);
    setDragDropState(questionIndex.toString(), resetState);
    onAnswerChange(resetState);
  };

  // Handle media controls
  const handleAudioPlay = (audioId: string) => {
    const audio = audioRefs.current[audioId];
    if (audio) {
      if (mediaStates[audioId]?.isPlaying) {
        audio.pause();
      } else {
        audio.play();
      }
    }
  };

  const handleAudioTimeUpdate = (audioId: string) => {
    const audio = audioRefs.current[audioId];
    if (audio) {
      setMediaStates(prev => ({
        ...prev,
        [audioId]: {
          ...prev[audioId],
          currentTime: audio.currentTime,
          duration: audio.duration
        }
      }));
    }
  };

  // Render media content
  const renderMediaContent = (media: any) => {
    if (!media) return null;

    switch (media.type) {
      case 'image':
        return (
          <div className="mb-4">
            <img 
              src={media.url} 
              alt={media.alt || 'Question image'}
              className="max-w-full h-auto rounded-lg shadow-sm"
              style={{ maxHeight: '300px' }}
            />
            {media.caption && (
              <p className="text-sm text-gray-600 mt-2 italic">{media.caption}</p>
            )}
          </div>
        );
      
      case 'audio':
        const audioState = mediaStates[media.id] || { isPlaying: false, currentTime: 0, duration: 0 };
        return (
          <div className="mb-4 p-4 bg-gray-50 rounded-lg">
            <div className="flex items-center space-x-3">
              <button
                onClick={() => handleAudioPlay(media.id)}
                className="p-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors"
              >
                {audioState.isPlaying ? <Pause size={16} /> : <Play size={16} />}
              </button>
              
              <div className="flex-1">
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div 
                    className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                    style={{ 
                      width: `${audioState.duration ? (audioState.currentTime / audioState.duration) * 100 : 0}%` 
                    }}
                  />
                </div>
                <div className="flex justify-between text-xs text-gray-500 mt-1">
                  <span>{Math.floor(audioState.currentTime || 0)}s</span>
                  <span>{Math.floor(audioState.duration || 0)}s</span>
                </div>
              </div>
              
              <button
                onClick={() => {
                  setMediaStates(prev => ({
                    ...prev,
                    [media.id]: { ...prev[media.id], isMuted: !prev[media.id]?.isMuted }
                  }));
                }}
                className="p-2 text-gray-600 hover:text-gray-800"
              >
                {audioState.isMuted ? <VolumeX size={16} /> : <Volume2 size={16} />}
              </button>
            </div>
            
            <audio
              ref={el => { if (el) audioRefs.current[media.id] = el; }}
              src={media.url}
              onPlay={() => setMediaStates(prev => ({ ...prev, [media.id]: { ...prev[media.id], isPlaying: true } }))}
              onPause={() => setMediaStates(prev => ({ ...prev, [media.id]: { ...prev[media.id], isPlaying: false } }))}
              onTimeUpdate={() => handleAudioTimeUpdate(media.id)}
              muted={audioState.isMuted}
            />
          </div>
        );
      
      case 'video':
        return (
          <div className="mb-4">
            <video 
              controls 
              className="w-full max-h-64 rounded-lg shadow-sm"
              poster={media.poster}
            >
              <source src={media.url} type="video/mp4" />
              Browser Anda tidak mendukung video HTML5.
            </video>
            {media.caption && (
              <p className="text-sm text-gray-600 mt-2 italic">{media.caption}</p>
            )}
          </div>
        );
      
      default:
        return null;
    }
  };

  // Render drag and drop interface
  const renderDragDropInterface = () => {
    if (question.type !== 'drag_drop') return null;

    const dragDropItems = question.content?.dragDropItems || [];
    const dropZones = question.content?.dropZones || [];

    return (
      <div className="space-y-4">
        {/* Drag items */}
        <div className="p-4 bg-gray-50 rounded-lg">
          <h4 className="font-medium mb-3">
            {adminLanguage === 'indonesia' ? 'Seret item berikut:' : 'Drag the following items:'}
          </h4>
          <div className="flex flex-wrap gap-2">
            {dragDropItems.map((item, index) => (
              <div
                key={index}
                draggable
                className="px-3 py-2 bg-white border border-gray-300 rounded cursor-move hover:shadow-md transition-shadow"
              >
                {item.text}
              </div>
            ))}
          </div>
        </div>

        {/* Drop zones */}
        <div className="space-y-3">
          <h4 className="font-medium">
            {adminLanguage === 'indonesia' ? 'Letakkan di zona yang sesuai:' : 'Drop in appropriate zones:'}
          </h4>
          {dropZones.map((zone, index) => (
            <div
              key={index}
              className="min-h-[60px] p-4 border-2 border-dashed border-gray-300 rounded-lg bg-gray-50 hover:border-blue-400 transition-colors"
            >
              <div className="text-sm text-gray-600 mb-2">{zone.label}</div>
              <div className="min-h-[30px] bg-white rounded border border-gray-200">
                {/* Dropped items akan ditampilkan di sini */}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  // Render multimedia content
   const renderMultimedia = () => {
     const media = question.content?.media;
     if (!media) return null;

     return (
       <div className="mb-4">
         {media.type === 'image' && (
           <img 
             src={media.src} 
             alt={media.alt || 'Question image'} 
             className="max-w-full h-auto rounded-lg shadow-sm"
           />
         )}
         {media.type === 'video' && (
           <video 
             src={media.src} 
             controls 
             className="max-w-full h-auto rounded-lg shadow-sm"
           >
             Your browser does not support the video tag.
           </video>
         )}
         {media.type === 'audio' && (
           <audio 
             src={media.src} 
             controls 
             className="w-full"
           >
             Your browser does not support the audio tag.
           </audio>
         )}
       </div>
     );
   };

  // Render hint
  const renderHint = () => {
    const hint = question.content?.hint;
    if (!hint || !showHint) return null;

    return (
      <div className="mt-4 p-3 bg-yellow-50 border-l-4 border-yellow-400 rounded-r">
        <div className="flex items-start">
          <HelpCircle className="text-yellow-600 mr-2 mt-0.5" size={16} />
          <div>
            <p className="text-sm font-medium text-yellow-800">
              {adminLanguage === 'indonesia' ? 'Petunjuk:' : 'Hint:'}
            </p>
            <p className="text-sm text-yellow-700 mt-1">{hint}</p>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="space-y-4">
      {/* Multimedia content */}
      {renderMultimedia()}

      {/* Render berdasarkan tipe pertanyaan */}
      {question.type === 'drag_drop' ? renderDragDropInterface() : (
        <div className="space-y-3">
          {(question.options || question.content?.options || []).map((option, index) => {
            const isSelected = Array.isArray(selectedAnswers) 
              ? selectedAnswers.includes(index)
              : selectedAnswers === index;

            // Handle both string options and object options
            const optionText = typeof option === 'string' ? option : option.text;

            return (
              <div
                key={index}
                onClick={() => handleAnswerSelect(index)}
                className={cn(
                  'p-4 border-2 rounded-lg cursor-pointer transition-all duration-200',
                  isSelected
                    ? 'border-blue-500 bg-blue-50 shadow-md'
                    : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                )}
              >
                <div className="flex items-start space-x-3">
                  <div className={cn(
                    'flex-shrink-0 w-6 h-6 rounded-full border-2 flex items-center justify-center mt-0.5',
                    isSelected
                      ? 'border-blue-500 bg-blue-500'
                      : 'border-gray-300'
                  )}>
                    {isSelected && (
                      question.content?.multipleAnswers ? (
                        <Check className="text-white" size={14} />
                      ) : (
                        <div className="w-2 h-2 bg-white rounded-full" />
                      )
                    )}
                  </div>
                  
                  <div className="flex-1">
                    <p className="text-gray-900 leading-relaxed">
                      {optionText}
                    </p>
                    
                    {/* Tampilkan gambar jika ada */}
                    {typeof option === 'object' && option.image && (
                      <img 
                        src={option.image} 
                        alt={`Option ${index + 1}`}
                        className="mt-2 max-w-xs h-auto rounded border"
                      />
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Hint section */}
      {question.content?.hint && (
        <div className="flex justify-between items-center">
          <button
            onClick={() => setShowHint(!showHint)}
            className="text-sm text-blue-600 hover:text-blue-800 flex items-center"
          >
            <HelpCircle size={16} className="mr-1" />
            {showHint 
              ? (adminLanguage === 'indonesia' ? 'Sembunyikan petunjuk' : 'Hide hint')
              : (adminLanguage === 'indonesia' ? 'Tampilkan petunjuk' : 'Show hint')
            }
          </button>
        </div>
      )}
      
      {renderHint()}

      {/* Confidence indicator */}
      {showConfidence && (
        <div className="mt-4 p-3 bg-blue-50 rounded-lg">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium text-blue-900">
              {adminLanguage === 'indonesia' ? 'Tingkat keyakinan:' : 'Confidence level:'}
            </span>
            <div className="flex space-x-1">
              {[1, 2, 3, 4, 5].map((level) => (
                <Star
                  key={level}
                  size={16}
                  className={cn(
                    'cursor-pointer transition-colors',
                    confidence >= level ? 'text-yellow-400 fill-current' : 'text-gray-300'
                  )}
                  onClick={() => setConfidence(level)}
                />
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default EnhancedMCQComponent;