'use client';

import React, { useState, useEffect } from 'react';
import { 
  Play, 
  Pause, 
  RotateCcw, 
  Eye, 
  EyeOff, 
  Timer, 
  CheckCircle, 
  XCircle, 
  HelpCircle, 
  Star, 
  Heart, 
  Zap, 
  Target, 
  Puzzle, 
  Gamepad2, 
  Brain, 
  MousePointer,
  Volume2,
  VolumeX,
  Maximize,
  Minimize,
  Settings,
  BarChart3
} from 'lucide-react';
import { InteractiveQuestionData } from './EnhancedQuestionBuilder';
import { MultimediaFile } from './MultimediaManager';

interface QuizPreviewProps {
  questions: InteractiveQuestionData[];
  currentQuestionIndex?: number;
  onQuestionChange?: (index: number) => void;
  showAnswers?: boolean;
  showExplanations?: boolean;
  showBehaviorTracking?: boolean;
  className?: string;
}

interface PreviewState {
  currentIndex: number;
  selectedAnswers: { [questionId: string]: any };
  timeSpent: { [questionId: string]: number };
  startTime: number;
  isPlaying: boolean;
  showHints: { [questionId: string]: boolean };
  behaviorData: {
    mouseMovements: number;
    clickCount: number;
    focusLost: number;
    hesitationTime: number;
  };
}

export const QuizPreview: React.FC<QuizPreviewProps> = ({
  questions,
  currentQuestionIndex = 0,
  onQuestionChange,
  showAnswers = false,
  showExplanations = false,
  showBehaviorTracking = false,
  className = ''
}) => {
  const [previewState, setPreviewState] = useState<PreviewState>({
    currentIndex: currentQuestionIndex,
    selectedAnswers: {},
    timeSpent: {},
    startTime: Date.now(),
    isPlaying: false,
    showHints: {},
    behaviorData: {
      mouseMovements: 0,
      clickCount: 0,
      focusLost: 0,
      hesitationTime: 0
    }
  });

  const [isFullscreen, setIsFullscreen] = useState(false);
  const [soundEnabled, setSoundEnabled] = useState(true);
  const [currentTimer, setCurrentTimer] = useState(0);

  const currentQuestion = questions[previewState.currentIndex];

  // Timer effect
  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (previewState.isPlaying && currentQuestion?.interactiveConfig?.timeLimit) {
      interval = setInterval(() => {
        setCurrentTimer(prev => {
          if (prev >= (currentQuestion.interactiveConfig?.timeLimit || 0)) {
            setPreviewState(prev => ({ ...prev, isPlaying: false }));
            return 0;
          }
          return prev + 1;
        });
      }, 1000);
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [previewState.isPlaying, currentQuestion]);

  // Behavior tracking
  useEffect(() => {
    if (!showBehaviorTracking) return;

    const handleMouseMove = () => {
      setPreviewState(prev => ({
        ...prev,
        behaviorData: {
          ...prev.behaviorData,
          mouseMovements: prev.behaviorData.mouseMovements + 1
        }
      }));
    };

    const handleClick = () => {
      setPreviewState(prev => ({
        ...prev,
        behaviorData: {
          ...prev.behaviorData,
          clickCount: prev.behaviorData.clickCount + 1
        }
      }));
    };

    const handleBlur = () => {
      setPreviewState(prev => ({
        ...prev,
        behaviorData: {
          ...prev.behaviorData,
          focusLost: prev.behaviorData.focusLost + 1
        }
      }));
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('click', handleClick);
    window.addEventListener('blur', handleBlur);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('click', handleClick);
      window.removeEventListener('blur', handleBlur);
    };
  }, [showBehaviorTracking]);

  const handleAnswerSelect = (questionId: string, answer: any) => {
    setPreviewState(prev => ({
      ...prev,
      selectedAnswers: {
        ...prev.selectedAnswers,
        [questionId]: answer
      }
    }));
  };

  const toggleHints = (questionId: string) => {
    setPreviewState(prev => ({
      ...prev,
      showHints: {
        ...prev.showHints,
        [questionId]: !prev.showHints[questionId]
      }
    }));
  };

  const nextQuestion = () => {
    if (previewState.currentIndex < questions.length - 1) {
      const newIndex = previewState.currentIndex + 1;
      setPreviewState(prev => ({ ...prev, currentIndex: newIndex }));
      setCurrentTimer(0);
      onQuestionChange?.(newIndex);
    }
  };

  const prevQuestion = () => {
    if (previewState.currentIndex > 0) {
      const newIndex = previewState.currentIndex - 1;
      setPreviewState(prev => ({ ...prev, currentIndex: newIndex }));
      setCurrentTimer(0);
      onQuestionChange?.(newIndex);
    }
  };

  const resetPreview = () => {
    setPreviewState({
      currentIndex: 0,
      selectedAnswers: {},
      timeSpent: {},
      startTime: Date.now(),
      isPlaying: false,
      showHints: {},
      behaviorData: {
        mouseMovements: 0,
        clickCount: 0,
        focusLost: 0,
        hesitationTime: 0
      }
    });
    setCurrentTimer(0);
  };

  const togglePlayPause = () => {
    setPreviewState(prev => ({ ...prev, isPlaying: !prev.isPlaying }));
  };

  const renderMultimedia = (files?: MultimediaFile[]) => {
    if (!files || files.length === 0) return null;

    return (
      <div className="mb-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {files.map(file => (
            <div key={file.id} className="border rounded-lg overflow-hidden">
              {file.type === 'image' && (
                <img 
                  src={file.url} 
                  alt={file.name}
                  className="w-full h-48 object-cover"
                />
              )}
              {file.type === 'video' && (
                <video 
                  src={file.url}
                  controls
                  className="w-full h-48"
                  muted={!soundEnabled}
                />
              )}
              {file.type === 'audio' && (
                <div className="p-4 bg-gray-50">
                  <audio 
                    src={file.url}
                    controls
                    className="w-full"
                    muted={!soundEnabled}
                  />
                  <p className="text-sm text-gray-600 mt-2">{file.name}</p>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    );
  };

  const renderQuestionContent = () => {
    if (!currentQuestion) return null;

    const questionId = currentQuestion.id || previewState.currentIndex.toString();
    const selectedAnswer = previewState.selectedAnswers[questionId];

    return (
      <div className="space-y-6">
        {/* Question Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <span className="px-3 py-1 bg-blue-100 text-blue-800 text-sm font-medium rounded-full">
              Soal {previewState.currentIndex + 1} dari {questions.length}
            </span>
            <span className="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded">
              {currentQuestion.type.replace('_', ' ').toUpperCase()}
            </span>
            <span className="px-2 py-1 bg-green-100 text-green-700 text-xs rounded">
              {currentQuestion.points} poin
            </span>
          </div>
          
          {currentQuestion.interactiveConfig?.timeLimit && currentQuestion.interactiveConfig.timeLimit > 0 && (
            <div className="flex items-center gap-2">
              <Timer className="w-4 h-4 text-gray-600" />
              <span className={`text-sm font-mono ${
                currentTimer > (currentQuestion.interactiveConfig.timeLimit * 0.8) ? 'text-red-600' : 'text-gray-600'
              }`}>
                {Math.max(0, (currentQuestion.interactiveConfig.timeLimit || 0) - currentTimer)}s
              </span>
            </div>
          )}
        </div>

        {/* Question Title */}
        <div>
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            {currentQuestion.title}
          </h3>
          
          {/* Multimedia */}
          {renderMultimedia(currentQuestion.multimedia)}
        </div>

        {/* Question Type Specific Content */}
        {['multiple_choice', 'enhanced_mcq'].includes(currentQuestion.type) && (
          <div className="space-y-3">
            {currentQuestion.options?.map((option, index) => {
              const isSelected = Array.isArray(selectedAnswer) 
                ? selectedAnswer.includes(option.id)
                : selectedAnswer === option.id;
              const isCorrect = option.isCorrect;
              
              return (
                <label 
                  key={option.id} 
                  className={`flex items-start p-4 border-2 rounded-lg cursor-pointer transition-all ${
                    isSelected 
                      ? showAnswers 
                        ? isCorrect 
                          ? 'border-green-500 bg-green-50' 
                          : 'border-red-500 bg-red-50'
                        : 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <input
                    type={currentQuestion.interactiveConfig?.allowMultipleAnswers ? "checkbox" : "radio"}
                    name={`question-${questionId}`}
                    checked={isSelected}
                    onChange={() => {
                      if (currentQuestion.interactiveConfig?.allowMultipleAnswers) {
                        const currentAnswers = Array.isArray(selectedAnswer) ? selectedAnswer : [];
                        const newAnswers = isSelected 
                          ? currentAnswers.filter(id => id !== option.id)
                          : [...currentAnswers, option.id];
                        handleAnswerSelect(questionId, newAnswers);
                      } else {
                        handleAnswerSelect(questionId, option.id);
                      }
                    }}
                    className="w-4 h-4 text-blue-600 focus:ring-blue-500 mt-1"
                  />
                  <div className="ml-3 flex-1">
                    <span className="text-gray-900">{option.text}</span>
                    {showAnswers && isCorrect && (
                      <CheckCircle className="w-4 h-4 text-green-600 inline ml-2" />
                    )}
                    {showExplanations && option.explanation && (
                      <p className="text-sm text-gray-600 mt-1">{option.explanation}</p>
                    )}
                  </div>
                </label>
              );
            })}
          </div>
        )}

        {currentQuestion.type === 'essay' && (
          <div>
            <textarea
              value={selectedAnswer || ''}
              onChange={(e) => handleAnswerSelect(questionId, e.target.value)}
              placeholder="Tulis jawaban Anda di sini..."
              rows={6}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
            {showAnswers && currentQuestion.essayAnswer && (
              <div className="mt-3 p-3 bg-green-50 border border-green-200 rounded-lg">
                <p className="text-sm font-medium text-green-800 mb-1">Kunci Jawaban:</p>
                <p className="text-sm text-green-700">{currentQuestion.essayAnswer}</p>
              </div>
            )}
          </div>
        )}

        {['true_false', 'true_false_cepat'].includes(currentQuestion.type) && (
          <div className="flex gap-4">
            {[
              { value: true, label: 'Benar', color: 'green' },
              { value: false, label: 'Salah', color: 'red' }
            ].map(option => {
              const isSelected = selectedAnswer === option.value;
              const isCorrect = currentQuestion.trueFalseAnswer === option.value;
              
              return (
                <label 
                  key={option.value.toString()}
                  className={`flex-1 flex items-center justify-center p-4 border-2 rounded-lg cursor-pointer transition-all ${
                    isSelected 
                      ? showAnswers 
                        ? isCorrect 
                          ? 'border-green-500 bg-green-50' 
                          : 'border-red-500 bg-red-50'
                        : 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <input
                    type="radio"
                    name={`question-${questionId}`}
                    checked={isSelected}
                    onChange={() => handleAnswerSelect(questionId, option.value)}
                    className="w-4 h-4 text-blue-600 focus:ring-blue-500 mr-3"
                  />
                  <span className="font-medium">{option.label}</span>
                  {showAnswers && isCorrect && (
                    <CheckCircle className="w-4 h-4 text-green-600 ml-2" />
                  )}
                </label>
              );
            })}
          </div>
        )}

        {/* Special Interactive Types */}
        {currentQuestion.type === 'mini_survey_reflection' && (
          <div className="space-y-4">
            <div className="p-4 bg-purple-50 rounded-lg">
              <p className="text-sm font-medium text-purple-900 mb-3">
                Bagaimana perasaan Anda tentang materi ini?
              </p>
              <div className="flex justify-center gap-4">
                {['😢', '😐', '😊', '😍'].map((emoji, index) => (
                  <button
                    key={index}
                    onClick={() => handleAnswerSelect(questionId, index + 1)}
                    className={`text-3xl p-2 rounded-lg transition-transform hover:scale-110 ${
                      selectedAnswer === index + 1 ? 'bg-purple-200 scale-110' : ''
                    }`}
                  >
                    {emoji}
                  </button>
                ))}
              </div>
            </div>
            
            <textarea
              placeholder="Ceritakan refleksi Anda tentang pembelajaran ini..."
              rows={4}
              className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500"
            />
          </div>
        )}

        {currentQuestion.type === 'puzzle' && (
          <div className="p-6 bg-yellow-50 border-2 border-dashed border-yellow-300 rounded-lg text-center">
            <Puzzle className="w-12 h-12 text-yellow-600 mx-auto mb-3" />
            <p className="text-yellow-800 font-medium">Puzzle Interaktif</p>
            <p className="text-yellow-700 text-sm mt-1">
              Komponen puzzle akan dirender di sini dengan drag & drop functionality
            </p>
          </div>
        )}

        {currentQuestion.type === 'mini_simulation_rpg' && (
          <div className="p-6 bg-indigo-50 border-2 border-dashed border-indigo-300 rounded-lg text-center">
            <Gamepad2 className="w-12 h-12 text-indigo-600 mx-auto mb-3" />
            <p className="text-indigo-800 font-medium">Mini RPG Simulation</p>
            <p className="text-indigo-700 text-sm mt-1">
              Simulasi RPG dengan karakter dan storyline akan dirender di sini
            </p>
          </div>
        )}

        {/* Hints */}
        {currentQuestion.interactiveConfig?.enableHints && 
         currentQuestion.interactiveConfig.hints && 
         currentQuestion.interactiveConfig.hints.length > 0 && (
          <div className="mt-4">
            <button
              onClick={() => toggleHints(questionId)}
              className="flex items-center gap-2 text-blue-600 hover:text-blue-800 text-sm font-medium"
            >
              <HelpCircle className="w-4 h-4" />
              {previewState.showHints[questionId] ? 'Sembunyikan' : 'Lihat'} Hint 
              ({currentQuestion.interactiveConfig.hints.length})
            </button>
            
            {previewState.showHints[questionId] && (
              <div className="mt-2 space-y-2">
                {currentQuestion.interactiveConfig.hints.map((hint, index) => (
                  <div key={index} className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                    <p className="text-sm text-blue-800">
                      <strong>Hint {index + 1}:</strong> {hint}
                    </p>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Explanation */}
        {showExplanations && currentQuestion.explanation && (
          <div className="mt-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
            <p className="text-sm font-medium text-yellow-800 mb-2">Penjelasan:</p>
            <p className="text-sm text-yellow-700">{currentQuestion.explanation}</p>
          </div>
        )}
      </div>
    );
  };

  const renderBehaviorPanel = () => {
    if (!showBehaviorTracking) return null;

    return (
      <div className="bg-gray-50 border-l p-4 space-y-4">
        <h4 className="font-medium text-gray-900 flex items-center gap-2">
          <BarChart3 className="w-4 h-4" />
          Behavior Tracking
        </h4>
        
        <div className="space-y-3 text-sm">
          <div className="flex justify-between">
            <span className="text-gray-600">Mouse Movements:</span>
            <span className="font-medium">{previewState.behaviorData.mouseMovements}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-gray-600">Clicks:</span>
            <span className="font-medium">{previewState.behaviorData.clickCount}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-gray-600">Focus Lost:</span>
            <span className="font-medium">{previewState.behaviorData.focusLost}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-gray-600">Time Spent:</span>
            <span className="font-medium">{Math.floor((Date.now() - previewState.startTime) / 1000)}s</span>
          </div>
        </div>
      </div>
    );
  };

  if (questions.length === 0) {
    return (
      <div className={`bg-white rounded-lg border p-8 text-center ${className}`}>
        <Eye className="w-12 h-12 text-gray-400 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">Tidak Ada Soal</h3>
        <p className="text-gray-600">Tambahkan soal untuk melihat preview</p>
      </div>
    );
  }

  return (
    <div className={`bg-white rounded-lg border ${isFullscreen ? 'fixed inset-0 z-50' : ''} ${className}`}>
      {/* Header Controls */}
      <div className="p-4 border-b bg-gray-50 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <button
            onClick={togglePlayPause}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-colors ${
              previewState.isPlaying 
                ? 'bg-red-600 text-white hover:bg-red-700' 
                : 'bg-green-600 text-white hover:bg-green-700'
            }`}
          >
            {previewState.isPlaying ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
            {previewState.isPlaying ? 'Pause' : 'Start'} Preview
          </button>
          
          <button
            onClick={resetPreview}
            className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
          >
            <RotateCcw className="w-4 h-4" />
            Reset
          </button>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => setSoundEnabled(!soundEnabled)}
            className="p-2 text-gray-600 hover:text-gray-800 transition-colors"
          >
            {soundEnabled ? <Volume2 className="w-4 h-4" /> : <VolumeX className="w-4 h-4" />}
          </button>
          
          <button
            onClick={() => setIsFullscreen(!isFullscreen)}
            className="p-2 text-gray-600 hover:text-gray-800 transition-colors"
          >
            {isFullscreen ? <Minimize className="w-4 h-4" /> : <Maximize className="w-4 h-4" />}
          </button>
        </div>
      </div>

      <div className="flex">
        {/* Main Content */}
        <div className="flex-1 p-6">
          {renderQuestionContent()}
          
          {/* Navigation */}
          <div className="flex items-center justify-between mt-8 pt-6 border-t">
            <button
              onClick={prevQuestion}
              disabled={previewState.currentIndex === 0}
              className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              Sebelumnya
            </button>
            
            <div className="flex items-center gap-2">
              {questions.map((_, index) => (
                <button
                  key={index}
                  onClick={() => {
                    setPreviewState(prev => ({ ...prev, currentIndex: index }));
                    setCurrentTimer(0);
                    onQuestionChange?.(index);
                  }}
                  className={`w-8 h-8 rounded-full text-sm font-medium transition-colors ${
                    index === previewState.currentIndex
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                  }`}
                >
                  {index + 1}
                </button>
              ))}
            </div>
            
            <button
              onClick={nextQuestion}
              disabled={previewState.currentIndex === questions.length - 1}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              Selanjutnya
            </button>
          </div>
        </div>

        {/* Behavior Tracking Panel */}
        {renderBehaviorPanel()}
      </div>
    </div>
  );
};