import React, { useState, useEffect, useRef } from 'react';
import { useExam } from '../../contexts/ExamContext';
import { InteractiveQuestion } from '../../types';
import { cn } from '../../utils/cn';
import { 
  Puzzle, 
  RotateCcw, 
  Check, 
  X, 
  Shuffle, 
  Lightbulb,
  Timer,
  Target,
  Move,
  Lock,
  Unlock
} from 'lucide-react';

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

interface PuzzlePiece {
  id: string;
  content: string;
  correctPosition: number | string;
  currentPosition: number | string;
  isLocked?: boolean;
}

interface PuzzleState {
  pieces: PuzzlePiece[];
  isComplete: boolean;
  moves: number;
  startTime: number;
  hints: number;
}

const PuzzleQuestion: React.FC<PuzzleQuestionProps> = ({
  question,
  questionIndex,
  onAnswerChange,
  adminLanguage = 'id'
}) => {
  const { state, setPuzzleState } = useExam();
  const [localPuzzleState, setLocalPuzzleState] = useState<PuzzleState | null>(null);
  const [draggedPiece, setDraggedPiece] = useState<string | null>(null);
  const [selectedPieces, setSelectedPieces] = useState<string[]>([]);
  const [showHint, setShowHint] = useState(false);
  const [hintMessage, setHintMessage] = useState('');
  const [hoveredDropZone, setHoveredDropZone] = useState<string | null>(null); // Add hover state
  const puzzleRef = useRef<HTMLDivElement>(null);

  // Initialize puzzle
  useEffect(() => {
    if (question.puzzleData && !localPuzzleState) {
      const savedState = state.puzzleStates?.[questionIndex];
      if (savedState) {
        setLocalPuzzleState(savedState);
      } else {
        initializePuzzle();
      }
    }
  }, [question.puzzleData, questionIndex]);

  // Initialize puzzle berdasarkan tipe
  const initializePuzzle = () => {
    if (!question.puzzleData) return;

    let pieces: PuzzlePiece[] = [];
    
    switch (question.puzzleData.type) {
      case 'jigsaw':
        if (question.puzzleData.pieces) {
          pieces = question.puzzleData.pieces.map((piece, index) => ({
            id: piece.id,
            content: piece.content,
            correctPosition: piece.correctPosition,
            currentPosition: index,
            isLocked: piece.isLocked || false
          }));
          // Shuffle pieces yang tidak terkunci
          const unlockedPieces = pieces.filter(p => !p.isLocked);
          const shuffledPositions = shuffleArray(Array.from(Array(unlockedPieces.length).keys()));
          unlockedPieces.forEach((piece, index) => {
            piece.currentPosition = shuffledPositions[index];
          });
        }
        break;
        
      case 'sequence':
        if (question.puzzleData.sequence) {
          pieces = question.puzzleData.sequence.map((item, index) => ({
            id: `seq-${index}`,
            content: item,
            correctPosition: index,
            currentPosition: index
          }));
          // Shuffle sequence
          const shuffledSequence = shuffleArray([...pieces]);
          shuffledSequence.forEach((piece, index) => {
            piece.currentPosition = index;
          });
          pieces = shuffledSequence;
        }
        break;
        
      case 'word_puzzle':
        if (question.puzzleData.words && question.puzzleData.correctOrder) {
          pieces = question.puzzleData.words.map((word, index) => ({
            id: `word-${index}`,
            content: word,
            correctPosition: question.puzzleData!.correctOrder![index],
            currentPosition: index
          }));
        }
        break;
        
      case 'slider':
        if (question.puzzleData.sliders) {
          pieces = question.puzzleData.sliders.map((slider, index) => ({
            id: slider.id,
            content: slider.label,
            correctPosition: slider.correctValue,
            currentPosition: Math.floor((slider.minValue + slider.maxValue) / 2), // Start at middle value
            isLocked: false
          }));
        }
        break;
    }

    const newState: PuzzleState = {
      pieces,
      isComplete: false,
      moves: 0,
      startTime: Date.now(),
      hints: 0
    };

    setLocalPuzzleState(newState);
    setPuzzleState(questionIndex.toString(), newState);
  };

  // Shuffle array utility
  const shuffleArray = (array: any[]) => {
    const shuffled = [...array];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled;
  };

  // Handle piece movement
  const movePiece = (fromIndex: number, toIndex: number) => {
    if (!localPuzzleState) return;
    
    const newPieces = [...localPuzzleState.pieces];
    const piece = newPieces[fromIndex];
    
    if (piece.isLocked) return;

    // Swap positions
    [newPieces[fromIndex], newPieces[toIndex]] = [newPieces[toIndex], newPieces[fromIndex]];
    
    // Update current positions
    newPieces[fromIndex].currentPosition = fromIndex;
    newPieces[toIndex].currentPosition = toIndex;

    const isComplete = checkCompletion(newPieces);
    
    const newState: PuzzleState = {
      ...localPuzzleState,
      pieces: newPieces,
      isComplete,
      moves: localPuzzleState.moves + 1
    };

    setLocalPuzzleState(newState);
    setPuzzleState(questionIndex.toString(), newState);
    onAnswerChange(newState);
  };

  // Check if puzzle is complete
  const checkCompletion = (pieces: PuzzlePiece[]): boolean => {
    const puzzleType = question.puzzleData?.type;
    
    if (puzzleType === 'slider') {
      const sliders = question.puzzleData?.sliders || [];
      return pieces.every(piece => {
        const slider = sliders.find(s => s.id === piece.id);
        if (!slider) return false;
        
        // Ensure both positions are numbers for arithmetic operations
        const currentPos = typeof piece.currentPosition === 'number' ? piece.currentPosition : 0;
        const correctPos = typeof piece.correctPosition === 'number' ? piece.correctPosition : 0;
        
        // Allow tolerance of ±1 for correct value
        const tolerance = 1;
        return Math.abs(currentPos - correctPos) <= tolerance;
      });
    }
    
    return pieces.every(piece => piece.currentPosition === piece.correctPosition);
  };

  // Handle drag start
  const handleDragStart = (e: React.DragEvent, pieceId: string) => {
    console.log('🚀 DRAG START:', {
      pieceId,
      draggedPiece: draggedPiece,
      localPuzzleState: localPuzzleState?.pieces?.length || 0,
      targetAreas: question.puzzleData?.targetAreas?.length || 0
    });
    setDraggedPiece(pieceId);
    e.dataTransfer.setData('text/plain', pieceId);
    e.dataTransfer.effectAllowed = 'move';
  };

  // Handle drop in sequence puzzle
  const handleDropInSequence = (e: React.DragEvent, targetPosition: number) => {
    e.preventDefault();
    if (!localPuzzleState) return;
    
    const pieceId = e.dataTransfer.getData('text/plain');
    const piece = localPuzzleState.pieces.find(p => p.id === pieceId);
    
    if (!piece || piece.isLocked) return;
    
    let newPieces = [...localPuzzleState.pieces];
    
    // Find if there's already a piece in the target position
    const existingPiece = localPuzzleState.pieces.find(p => p.correctPosition === targetPosition);
    
    if (existingPiece && existingPiece.currentPosition === targetPosition) {
      // Swap positions
      const pieceIndex = newPieces.findIndex(p => p.id === pieceId);
      const existingIndex = newPieces.findIndex(p => p.id === existingPiece.id);
      
      newPieces[pieceIndex].currentPosition = targetPosition;
      newPieces[existingIndex].currentPosition = piece.currentPosition;
    } else {
      // Just move the piece
      const pieceIndex = newPieces.findIndex(p => p.id === pieceId);
      newPieces[pieceIndex].currentPosition = targetPosition;
    }
    
    const isComplete = checkCompletion(newPieces);
    
    const newState: PuzzleState = {
      ...localPuzzleState,
      pieces: newPieces,
      isComplete,
      moves: localPuzzleState.moves + 1
    };

    setLocalPuzzleState(newState);
    setPuzzleState(questionIndex.toString(), newState);
    onAnswerChange(newState);
    setDraggedPiece(null);
  };

  // Handle drop in matching puzzle
  const handleDropInMatching = (e: React.DragEvent, targetPosition: number) => {
    e.preventDefault();
    setHoveredDropZone(null); // Clear hover state
    if (!localPuzzleState) return;
    
    const pieceId = e.dataTransfer.getData('text/plain');
    const piece = localPuzzleState.pieces.find(p => p.id === pieceId);
    
    if (!piece || piece.isLocked) return;
    
    // Get the target area ID from puzzleData
    const targetAreaId = question.puzzleData?.targetAreas?.[targetPosition]?.id;
    if (!targetAreaId) return;
    
    const newPieces = [...localPuzzleState.pieces];
    const pieceIndex = newPieces.findIndex(p => p.id === pieceId);
    
    // Clear any previous placement of this piece in other positions
    newPieces.forEach((p, idx) => {
      if (p.id === pieceId) {
        // Reset this piece's position
        p.currentPosition = p.id; // Reset to original position (piece ID)
      }
    });
    
    // Clear any other piece that might be in this target position
    newPieces.forEach((p, idx) => {
      if (p.currentPosition === targetAreaId && p.id !== pieceId) {
        p.currentPosition = p.id; // Reset to original position
      }
    });
    
    // Set the new position using the target area ID
    newPieces[pieceIndex].currentPosition = targetAreaId;
    
    const isComplete = checkCompletion(newPieces);
    
    const newState: PuzzleState = {
      ...localPuzzleState,
      pieces: newPieces,
      isComplete,
      moves: localPuzzleState.moves + 1
    };

    setLocalPuzzleState(newState);
    setPuzzleState(questionIndex.toString(), newState);
    onAnswerChange(newState);
    setDraggedPiece(null);
  };

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

  // Handle drag enter for hover effect
  const handleDragEnter = (e: React.DragEvent, targetId: string) => {
    e.preventDefault();
    if (draggedPiece) {
      setHoveredDropZone(targetId);
    }
  };

  // Handle drag leave for hover effect
  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    // Only clear hover if we're actually leaving the drop zone
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
    const x = e.clientX;
    const y = e.clientY;
    
    if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
      setHoveredDropZone(null);
    }
  };

  // Handle drop
  const handleDrop = (e: React.DragEvent, targetIndex: number) => {
    e.preventDefault();
    if (!localPuzzleState) return;
    
    const pieceId = e.dataTransfer.getData('text/plain');
    const sourceIndex = localPuzzleState.pieces.findIndex(p => p.id === pieceId);
    
    if (sourceIndex !== -1 && sourceIndex !== targetIndex) {
      movePiece(sourceIndex, targetIndex);
    }
    
    setDraggedPiece(null);
  };

  // Handle piece selection (for touch devices)
  const handlePieceSelection = (pieceId: string) => {
    if (!localPuzzleState) return;
    
    if (selectedPieces.length === 0) {
      setSelectedPieces([pieceId]);
    } else if (selectedPieces.length === 1) {
      const firstPieceIndex = localPuzzleState.pieces.findIndex(p => p.id === selectedPieces[0]);
      const secondPieceIndex = localPuzzleState.pieces.findIndex(p => p.id === pieceId);
      
      if (firstPieceIndex !== secondPieceIndex) {
        movePiece(firstPieceIndex, secondPieceIndex);
      }
      
      setSelectedPieces([]);
    }
  };

  // Reset puzzle
  const resetPuzzle = () => {
    initializePuzzle();
  };

  // Shuffle puzzle
  const shufflePuzzle = () => {
    if (!localPuzzleState) return;
    
    const unlockedPieces = localPuzzleState.pieces.filter(p => !p.isLocked);
    const shuffledPositions = shuffleArray(unlockedPieces.map(p => p.currentPosition));
    
    const newPieces = [...localPuzzleState.pieces];
    unlockedPieces.forEach((piece, index) => {
      const pieceIndex = newPieces.findIndex(p => p.id === piece.id);
      newPieces[pieceIndex].currentPosition = shuffledPositions[index];
    });

    const newState: PuzzleState = {
      ...localPuzzleState,
      pieces: newPieces,
      isComplete: false,
      moves: localPuzzleState.moves + 1
    };

    setLocalPuzzleState(newState);
    setPuzzleState(questionIndex.toString(), newState);
  };

  // Show hint
  const showPuzzleHint = () => {
    if (!localPuzzleState || localPuzzleState.hints >= 3) return; // Maksimal 3 hint

    const incorrectPieces = localPuzzleState.pieces.filter(
      piece => piece.currentPosition !== piece.correctPosition && !piece.isLocked
    );
    
    if (incorrectPieces.length > 0) {
      const randomPiece = incorrectPieces[Math.floor(Math.random() * incorrectPieces.length)];
      const correctIndex = localPuzzleState.pieces.findIndex(p => p.correctPosition === randomPiece.correctPosition);
      
      if (correctIndex !== -1) {
        movePiece(localPuzzleState.pieces.findIndex(p => p.id === randomPiece.id), correctIndex);
        
        setLocalPuzzleState(prev => {
          if (!prev) return null;
          return {
            ...prev,
            hints: prev.hints + 1
          };
        });
      }
    }
  };

  // Render puzzle piece
  const renderPuzzlePiece = (piece: PuzzlePiece, index: number) => {
    const isSelected = selectedPieces.includes(piece.id);
    const isDragging = draggedPiece === piece.id;
    const isCorrect = piece.currentPosition === piece.correctPosition;
    const isDropTarget = draggedPiece && draggedPiece !== piece.id;
    
    return (
      <div
        key={piece.id}
        draggable={!piece.isLocked}
        onDragStart={(e) => handleDragStart(e, piece.id)}
        onDragOver={handleDragOver}
        onDrop={(e) => handleDrop(e, index)}
        onClick={() => handlePieceSelection(piece.id)}
        className={cn(
          'relative p-4 border-2 rounded-lg cursor-pointer transition-all duration-200',
          'min-h-16 flex items-center justify-center text-center',
          'transform hover:scale-105 active:scale-95',
          isDragging && 'opacity-30 scale-110 rotate-2 shadow-2xl z-10',
          isSelected && 'ring-4 ring-blue-500 ring-offset-2 shadow-lg scale-105',
          isDropTarget && 'border-dashed border-blue-500 bg-blue-50 scale-105',
          isCorrect && localPuzzleState?.isComplete && 'bg-green-100 border-green-500 shadow-md',
          piece.isLocked && 'bg-gray-100 border-gray-300 cursor-not-allowed opacity-60',
          !piece.isLocked && !isCorrect && 'bg-white border-gray-300 hover:border-blue-400 hover:shadow-lg hover:bg-blue-50',
          !piece.isLocked && isCorrect && !localPuzzleState?.isComplete && 'bg-green-50 border-green-400 shadow-sm'
        )}
        style={{
          transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
        }}
      >
        {/* Drag indicator overlay */}
        {isDragging && (
          <div className="absolute inset-0 bg-blue-200 bg-opacity-50 rounded-lg flex items-center justify-center">
            <Move size={24} className="text-blue-600 animate-pulse" />
          </div>
        )}
        
        {/* Drop zone indicator */}
        {isDropTarget && (
          <div className="absolute inset-0 border-2 border-dashed border-blue-400 rounded-lg animate-pulse">
            <div className="absolute inset-0 bg-blue-100 bg-opacity-30 rounded-lg flex items-center justify-center">
              <div className="text-blue-600 text-xs font-medium">Lepas di sini</div>
            </div>
          </div>
        )}
        
        {/* Selection indicator */}
        {isSelected && (
          <div className="absolute -top-2 -right-2 bg-blue-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs font-bold animate-bounce">
            1
          </div>
        )}
        
        {/* Position number indicator */}
        <div className="absolute -top-2 -left-2 bg-gray-600 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs font-bold">
          {index + 1}
        </div>
        
        {/* Lock indicator */}
        {piece.isLocked && (
          <div className="absolute top-1 right-1 bg-gray-500 rounded-full p-1">
            <Lock size={12} className="text-white" />
          </div>
        )}
        
        {/* Correct indicator */}
        {isCorrect && localPuzzleState?.isComplete && (
          <div className="absolute top-1 right-1 bg-green-500 rounded-full p-1 animate-pulse">
            <Check size={12} className="text-white" />
          </div>
        )}
        
        {/* Piece content */}
        <div className="w-full z-10 relative">
          {question.puzzleData?.type === 'jigsaw' && piece.content.startsWith('data:') ? (
            <img 
              src={piece.content} 
              alt={`Puzzle piece ${index + 1}`}
              className="w-full h-auto rounded"
            />
          ) : (
            <span className={cn(
              "text-sm font-medium",
              isDragging ? "text-blue-600" : "text-gray-900",
              isSelected && "text-blue-700 font-bold"
            )}>
              {piece.content}
            </span>
          )}
        </div>
        
        {/* Move indicator */}
        {!piece.isLocked && !isDragging && (
          <div className="absolute bottom-1 right-1 opacity-50 group-hover:opacity-100 transition-opacity">
            <Move size={12} className="text-gray-400" />
          </div>
        )}
        
        {/* Hover instruction */}
        {!piece.isLocked && !isDragging && !isSelected && (
          <div className="absolute inset-0 bg-black bg-opacity-0 hover:bg-opacity-10 rounded-lg flex items-center justify-center opacity-0 hover:opacity-100 transition-all duration-200">
            <div className="text-xs text-gray-700 font-medium bg-white bg-opacity-90 px-2 py-1 rounded shadow">
              Seret atau ketuk
            </div>
          </div>
        )}
      </div>
    );
  };

  // Render puzzle grid with proper drop zones
  const renderPuzzleGrid = () => {
    if (!localPuzzleState) return null;
    
    const puzzleType = question.puzzleData?.type;
    const contentPuzzleType = (question.content as any)?.puzzleType;
    
    console.log('🎯 PUZZLE TYPE CHECK:', {
      puzzleDataType: puzzleType,
      contentPuzzleType: contentPuzzleType,
      hasTargetAreas: !!question.puzzleData?.targetAreas?.length,
      targetAreasCount: question.puzzleData?.targetAreas?.length || 0
    });
    
    if (puzzleType === 'sequence') {
      return renderSequencePuzzle();
    } else if (puzzleType === 'jigsaw' || contentPuzzleType === 'matching') {
      return renderMatchingPuzzle();
    } else if (puzzleType === 'slider') {
      return renderSliderPuzzle();
    }
    
    // Fallback to original grid
    const gridCols = question.puzzleData?.gridSize?.cols || Math.ceil(Math.sqrt(localPuzzleState.pieces.length));
    const gridRows = question.puzzleData?.gridSize?.rows || Math.ceil(localPuzzleState.pieces.length / gridCols);
    
    return (
      <div 
        ref={puzzleRef}
        className="grid gap-2 p-4 bg-gray-50 rounded-lg"
        style={{ 
          gridTemplateColumns: `repeat(${gridCols}, 1fr)`,
          gridTemplateRows: `repeat(${gridRows}, 1fr)`
        }}
      >
        {localPuzzleState.pieces.map((piece, index) => renderPuzzlePiece(piece, index))}
      </div>
    );
  };

  // Render sequence puzzle with clear drop zones
  const renderSequencePuzzle = () => {
    if (!localPuzzleState) return null;
    
    const sortedPieces = [...localPuzzleState.pieces].sort((a, b) => {
      const aPos = typeof a.currentPosition === 'number' ? a.currentPosition : 0;
      const bPos = typeof b.currentPosition === 'number' ? b.currentPosition : 0;
      return aPos - bPos;
    });
    
    return (
      <div className="space-y-4">
        {/* Draggable pieces area */}
        <div className="p-4 bg-blue-50 border-2 border-blue-200 rounded-lg">
          <h4 className="text-sm font-semibold text-blue-900 mb-3 flex items-center">
            <Move className="mr-2" size={16} />
            Seret item berikut ke urutan yang benar:
          </h4>
          <div className="flex flex-wrap gap-2">
            {sortedPieces.map((piece, index) => (
              <div
                key={piece.id}
                draggable={!piece.isLocked}
                onDragStart={(e) => handleDragStart(e, piece.id)}
                onClick={() => handlePieceSelection(piece.id)}
                className={cn(
                  'px-4 py-3 bg-white border-2 rounded-lg cursor-move transition-all duration-200',
                  'hover:shadow-lg hover:scale-105 active:scale-95',
                  draggedPiece === piece.id && 'opacity-30 scale-110 rotate-2 shadow-2xl z-10',
                  selectedPieces.includes(piece.id) && 'ring-4 ring-blue-500 ring-offset-2 shadow-lg scale-105',
                  piece.isLocked && 'bg-gray-100 border-gray-300 cursor-not-allowed opacity-60',
                  !piece.isLocked && 'border-blue-300 hover:border-blue-500'
                )}
              >
                <span className="text-sm font-medium text-gray-900">{piece.content}</span>
                {piece.isLocked && (
                  <Lock size={12} className="inline ml-2 text-gray-500" />
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Drop zones for sequence */}
        <div className="p-4 bg-green-50 border-2 border-green-200 rounded-lg">
          <h4 className="text-sm font-semibold text-green-900 mb-3 flex items-center">
            <Target className="mr-2" size={16} />
            Urutan yang benar:
          </h4>
          <div className="grid gap-3" style={{ gridTemplateColumns: `repeat(${localPuzzleState.pieces.length}, 1fr)` }}>
            {Array.from({ length: localPuzzleState.pieces.length }, (_, index) => {
              const pieceInPosition = localPuzzleState.pieces.find(p => p.correctPosition === index);
              const isCorrectlyPlaced = pieceInPosition && pieceInPosition.currentPosition === index;
              
              return (
                <div
                  key={index}
                  onDragOver={handleDragOver}
                  onDrop={(e) => handleDropInSequence(e, index)}
                  className={cn(
                    'min-h-16 p-3 border-2 border-dashed rounded-lg transition-all duration-200',
                    'flex items-center justify-center text-center relative',
                    draggedPiece && 'border-blue-400 bg-blue-50 scale-105',
                    isCorrectlyPlaced && 'bg-green-100 border-green-400 border-solid',
                    !isCorrectlyPlaced && !draggedPiece && 'border-gray-300 bg-gray-50',
                    !isCorrectlyPlaced && draggedPiece && 'hover:border-blue-500 hover:bg-blue-100'
                  )}
                >
                  {/* Position number */}
                  <div className="absolute -top-2 -left-2 bg-green-600 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs font-bold">
                    {index + 1}
                  </div>
                  
                  {/* Drop zone content */}
                  {isCorrectlyPlaced ? (
                    <div className="flex items-center space-x-2">
                      <span className="text-sm font-medium text-green-900">{pieceInPosition.content}</span>
                      <Check size={16} className="text-green-600" />
                    </div>
                  ) : (
                    <div className="text-xs text-gray-500 font-medium">
                      {draggedPiece ? 'Lepas di sini' : 'Kosong'}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  };

  // Render matching puzzle with clear areas
  const renderMatchingPuzzle = () => {
    if (!localPuzzleState) return null;
    
    const items = localPuzzleState.pieces;
    const targetAreas = question.puzzleData?.targetAreas || [];
    
    console.log('🎮 RENDER MATCHING PUZZLE:', {
      questionId: question.id,
      questionContent: question.content,
      itemsCount: items?.length || 0,
      targetAreasCount: targetAreas?.length || 0,
      items: items?.map(item => ({ 
        id: item.id, 
        content: item.content, 
        correctPosition: item.correctPosition,
        currentPosition: item.currentPosition,
        isLocked: item.isLocked 
      })),
      targetAreas: targetAreas?.map(area => ({ id: area.id, label: area.label })),
      draggedPiece,
      hoveredDropZone,
      fullPuzzleData: question.puzzleData
    });
    
    return (
      <div className="grid md:grid-cols-2 gap-6">
        {/* Items to match */}
        <div className="p-4 bg-blue-50 border-2 border-blue-200 rounded-lg">
          <h4 className="text-sm font-semibold text-blue-900 mb-3 flex items-center">
            <Move className="mr-2" size={16} />
            Item yang akan dicocokkan:
          </h4>
          <div className="space-y-2">
            {items.map((piece, index) => (
              <div
                key={piece.id}
                draggable={!piece.isLocked}
                onDragStart={(e) => handleDragStart(e, piece.id)}
                onClick={() => handlePieceSelection(piece.id)}
                className={cn(
                  'p-3 bg-white border-2 rounded-lg cursor-move transition-all duration-200',
                  'hover:shadow-md hover:scale-102 active:scale-98',
                  draggedPiece === piece.id && 'opacity-30 scale-105 rotate-1 shadow-xl z-10',
                  selectedPieces.includes(piece.id) && 'ring-4 ring-blue-500 ring-offset-2 shadow-lg',
                  piece.isLocked && 'bg-gray-100 border-gray-300 cursor-not-allowed opacity-60',
                  !piece.isLocked && 'border-blue-300 hover:border-blue-500'
                )}
              >
                <span className="text-sm font-medium text-gray-900">{piece.content}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Drop zones for definitions */}
        <div className="p-4 bg-green-50 border-2 border-green-200 rounded-lg">
          <h4 className="text-sm font-semibold text-green-900 mb-3 flex items-center">
            <Target className="mr-2" size={16} />
            Cocokkan dengan definisi:
          </h4>
          <div className="space-y-6">
            {targetAreas.map((targetArea, index) => {
              console.log('🎯 RENDERING TARGET AREA:', { 
                targetArea: targetArea.id, 
                index, 
                label: targetArea.label,
                hoveredDropZone,
                isHovered: hoveredDropZone === targetArea.id
              });
              const targetAreaId = targetArea.id;
              const matchedPiece = items.find(p => p.currentPosition === targetAreaId);
              const isCorrect = matchedPiece && matchedPiece.correctPosition === targetAreaId;
              const isHovered = hoveredDropZone === targetAreaId;
              
              return (
                <div
                  key={targetAreaId}
                  onDragOver={(e) => {
                     e.preventDefault();
                     e.stopPropagation();
                     console.log('📋 DRAG OVER:', { targetAreaId, draggedPiece, hoveredDropZone });
                   }}
                   onDragEnter={(e) => {
                     e.preventDefault();
                     e.stopPropagation();
                     console.log('📥 DRAG ENTER:', { targetAreaId, draggedPiece });
                     if (draggedPiece) {
                       setHoveredDropZone(targetAreaId);
                       console.log('✅ SET HOVERED ZONE:', targetAreaId);
                     }
                   }}
                   onDragLeave={(e) => {
                     e.preventDefault();
                     e.stopPropagation();
                     console.log('📤 DRAG LEAVE:', { targetAreaId, hoveredDropZone });
                     // Check if we're really leaving the drop zone
                     const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
                     const x = e.clientX;
                     const y = e.clientY;
                     if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
                       setHoveredDropZone(null);
                       console.log('❌ CLEAR HOVERED ZONE');
                     }
                   }}
                   onDrop={(e) => {
                     e.preventDefault();
                     e.stopPropagation();
                     console.log('🎯 DROP EVENT:', { 
                       targetAreaId, 
                       index, 
                       draggedPiece,
                       dataTransfer: e.dataTransfer.getData('text/plain')
                     });
                     handleDropInMatching(e, index);
                     setHoveredDropZone(null);
                   }}
                  onClick={() => {
                    // Handle click-to-place for mobile devices
                    if (selectedPieces.length === 1) {
                      const selectedPieceId = selectedPieces[0];
                      const piece = items.find(p => p.id === selectedPieceId);
                      if (piece && !piece.isLocked) {
                        // Simulate drop event
                         const fakeEvent = {
                           preventDefault: () => {},
                           stopPropagation: () => {},
                           dataTransfer: {
                             getData: () => selectedPieceId
                           }
                         } as unknown as React.DragEvent;
                        console.log('Click-to-place triggered for:', selectedPieceId, 'to target:', targetAreaId);
                        handleDropInMatching(fakeEvent, index);
                        setSelectedPieces([]); // Clear selection
                      }
                    }
                  }}
                  className={cn(
                    'min-h-20 p-4 border-3 border-dashed rounded-xl transition-all duration-300',
                    'flex items-center justify-between relative cursor-pointer',
                    'bg-white shadow-lg hover:shadow-xl',
                    // Hover state when dragging
                    isHovered && draggedPiece && 'border-green-500 bg-green-100 scale-105 shadow-2xl ring-2 ring-green-300',
                    // Correct match state
                    isCorrect && 'bg-green-100 border-green-500 border-solid shadow-xl ring-2 ring-green-200',
                    // Default state
                    !isCorrect && !draggedPiece && selectedPieces.length === 0 && 'border-gray-500 bg-gray-50 hover:border-blue-400 hover:bg-blue-50',
                    // Dragging but not hovering this zone
                    !isCorrect && draggedPiece && !isHovered && 'border-gray-400 bg-gray-100 opacity-75',
                    // Selected piece ready to place
                    !isCorrect && selectedPieces.length === 1 && 'border-blue-500 bg-blue-100 hover:border-blue-600 hover:bg-blue-200 shadow-xl ring-2 ring-blue-300 animate-pulse'
                  )}
                >
                  {/* Definition label */}
                  <div className="flex-1">
                    <div className="text-xs text-gray-600 mb-1">Target {index + 1}:</div>
                    <div className="text-sm text-gray-800">
                      {targetArea.content || targetArea.label || `Target area ${index + 1}`}
                    </div>
                  </div>
                  
                  {/* Matched item or drop zone */}
                  <div className="ml-4 min-w-32">
                    {isCorrect ? (
                      <div className="flex items-center space-x-2 p-2 bg-green-200 rounded">
                        <span className="text-sm font-medium text-green-900">{matchedPiece.content}</span>
                        <Check size={16} className="text-green-600" />
                      </div>
                    ) : (
                      <div className={cn(
                        "p-4 border-2 border-dashed rounded-xl text-center transition-all duration-300 min-h-16",
                        "bg-gradient-to-br from-white to-gray-50 shadow-inner",
                        isHovered && draggedPiece ? "border-green-500 bg-gradient-to-br from-green-50 to-green-100 shadow-lg animate-bounce" : 
                        selectedPieces.length === 1 ? "border-blue-500 bg-gradient-to-br from-blue-50 to-blue-100 shadow-lg animate-pulse" : 
                        "border-gray-500 bg-gradient-to-br from-gray-50 to-gray-100 hover:border-blue-400 hover:from-blue-50 hover:to-blue-100"
                      )}>
                        <div className="text-sm font-bold text-gray-700 mb-1">
                          {isHovered && draggedPiece ? '🎯 LEPAS DI SINI!' : 
                           selectedPieces.length === 1 ? '👆 KLIK UNTUK MENEMPATKAN' : 
                           '📋 AREA DROP'}
                        </div>
                        <div className="text-xs text-gray-500">
                          {isHovered && draggedPiece ? 'Lepaskan item yang sedang diseret' : 
                           selectedPieces.length === 1 ? 'Klik untuk menempatkan item terpilih' : 
                           'Seret item ke sini atau klik setelah memilih'}
                        </div>
                        {matchedPiece && !isCorrect && (
                          <div className="text-sm text-orange-700 mt-2 font-medium bg-orange-100 p-2 rounded border border-orange-300">
                            ❌ {matchedPiece.content}
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  };

  // Render slider puzzle
  const renderSliderPuzzle = () => {
    if (!localPuzzleState) return null;
    
    const sliders = question.puzzleData?.sliders || [];
    
    const handleSliderChange = (sliderId: string, value: number) => {
      const newPieces = [...localPuzzleState.pieces];
      const pieceIndex = newPieces.findIndex(p => p.id === sliderId);
      
      if (pieceIndex !== -1) {
        newPieces[pieceIndex].currentPosition = value;
        
        const isComplete = checkSliderCompletion(newPieces);
        
        const newState: PuzzleState = {
          ...localPuzzleState,
          pieces: newPieces,
          isComplete,
          moves: localPuzzleState.moves + 1
        };

        setLocalPuzzleState(newState);
        setPuzzleState(questionIndex.toString(), newState);
        onAnswerChange(newState);
      }
    };

    const checkSliderCompletion = (pieces: PuzzlePiece[]) => {
      return pieces.every(piece => {
        const slider = sliders.find(s => s.id === piece.id);
        if (!slider) return false;
        
        // Ensure both positions are numbers for arithmetic operations
        const currentPos = typeof piece.currentPosition === 'number' ? piece.currentPosition : 0;
        const correctPos = typeof piece.correctPosition === 'number' ? piece.correctPosition : 0;
        
        // Allow tolerance of ±1 for correct value
        const tolerance = 1;
        return Math.abs(currentPos - correctPos) <= tolerance;
      });
    };

    return (
      <div className="space-y-6">
        <div className="p-4 bg-blue-50 border-2 border-blue-200 rounded-lg">
          <h4 className="text-sm font-semibold text-blue-900 mb-4 flex items-center">
            <Target className="mr-2" size={16} />
            Atur nilai yang tepat untuk setiap parameter:
          </h4>
          
          <div className="space-y-6">
            {sliders.map((slider, index) => {
              const piece = localPuzzleState.pieces.find(p => p.id === slider.id);
              const currentValue = typeof piece?.currentPosition === 'number' ? piece.currentPosition : slider.minValue;
              const isCorrect = piece && Math.abs(currentValue - slider.correctValue) <= 1;
              
              return (
                <div key={slider.id} className="space-y-3">
                  <div className="flex justify-between items-center">
                    <label className="text-sm font-medium text-gray-900">
                      {slider.label}
                    </label>
                    <div className={cn(
                      "px-3 py-1 rounded-full text-sm font-bold",
                      isCorrect ? "bg-green-100 text-green-800" : "bg-gray-100 text-gray-800"
                    )}>
                      {currentValue}{slider.unit}
                    </div>
                  </div>
                  
                  <div className="relative">
                    <input
                      type="range"
                      min={slider.minValue}
                      max={slider.maxValue}
                      value={currentValue}
                      onChange={(e) => handleSliderChange(slider.id, parseInt(e.target.value))}
                      className={cn(
                        "w-full h-2 rounded-lg appearance-none cursor-pointer",
                        "bg-gray-200 slider-thumb",
                        isCorrect ? "accent-green-500" : "accent-blue-500"
                      )}
                      style={{
                        background: `linear-gradient(to right, ${isCorrect ? '#10b981' : '#3b82f6'} 0%, ${isCorrect ? '#10b981' : '#3b82f6'} ${((currentValue - slider.minValue) / (slider.maxValue - slider.minValue)) * 100}%, #e5e7eb ${((currentValue - slider.minValue) / (slider.maxValue - slider.minValue)) * 100}%, #e5e7eb 100%)`
                      }}
                    />
                    
                    {/* Range labels */}
                    <div className="flex justify-between text-xs text-gray-500 mt-1">
                      <span>{slider.minValue}{slider.unit}</span>
                      <span className="text-green-600 font-medium">
                        Target: {slider.correctValue}{slider.unit}
                      </span>
                      <span>{slider.maxValue}{slider.unit}</span>
                    </div>
                  </div>
                  
                  {/* Correctness indicator */}
                  {isCorrect && (
                    <div className="flex items-center space-x-2 text-green-600">
                      <Check size={16} />
                      <span className="text-sm font-medium">Nilai sudah tepat!</span>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  };

  // Render puzzle stats
  const renderPuzzleStats = () => {
    if (!localPuzzleState) return null;
    
    const timeElapsed = Math.floor((Date.now() - localPuzzleState.startTime) / 1000);
    const minutes = Math.floor(timeElapsed / 60);
    const seconds = timeElapsed % 60;
    
    return (
      <div className="flex items-center justify-between text-sm text-gray-600 bg-gray-50 p-3 rounded">
        <div className="flex items-center space-x-4">
          <div className="flex items-center space-x-1">
            <Timer size={16} />
            <span>{minutes}:{seconds.toString().padStart(2, '0')}</span>
          </div>
          
          <div className="flex items-center space-x-1">
            <Target size={16} />
            <span>{localPuzzleState.moves} {adminLanguage === 'id' ? 'gerakan' : 'moves'}</span>
          </div>
          
          <div className="flex items-center space-x-1">
            <Lightbulb size={16} />
            <span>{localPuzzleState.hints}/3 {adminLanguage === 'id' ? 'petunjuk' : 'hints'}</span>
          </div>
        </div>
        
        <div className="flex items-center space-x-2">
          <button
            onClick={showPuzzleHint}
            disabled={localPuzzleState.hints >= 3 || localPuzzleState.isComplete}
            className="px-3 py-1 text-xs bg-yellow-100 text-yellow-800 rounded hover:bg-yellow-200 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {adminLanguage === 'id' ? 'Petunjuk' : 'Hint'}
          </button>
          
          <button
            onClick={shufflePuzzle}
            disabled={localPuzzleState.isComplete}
            className="px-3 py-1 text-xs bg-blue-100 text-blue-800 rounded hover:bg-blue-200 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <Shuffle size={12} />
          </button>
          
          <button
            onClick={resetPuzzle}
            className="px-3 py-1 text-xs bg-gray-100 text-gray-800 rounded hover:bg-gray-200"
          >
            <RotateCcw size={12} />
          </button>
        </div>
      </div>
    );
  };

  if (!question.puzzleData) {
    return (
      <div className="p-6 text-center text-gray-500">
        <Puzzle className="mx-auto mb-2" size={48} />
        <p>{adminLanguage === 'id' ? 'Data puzzle tidak tersedia' : 'Puzzle data not available'}</p>
      </div>
    );
  }

  if (!localPuzzleState) {
    return (
      <div className="p-6 text-center text-gray-500">
        <Puzzle className="mx-auto mb-2" size={48} />
        <p>{adminLanguage === 'id' ? 'Memuat puzzle...' : 'Loading puzzle...'}</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Tutorial untuk pertama kali */}
      {localPuzzleState.moves === 0 && (
        <div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
          <div className="flex items-start space-x-3">
            <div className="flex-shrink-0">
              <Lightbulb className="text-blue-600" size={20} />
            </div>
            <div className="flex-1">
              <h4 className="text-sm font-semibold text-blue-900 mb-2">
                Cara Bermain:
              </h4>
              <div className="space-y-1 text-xs text-blue-800">
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-blue-400 rounded-full"></div>
                  <span><strong>Desktop:</strong> Seret dan lepas potongan untuk memindahkannya</span>
                </div>
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-blue-400 rounded-full"></div>
                  <span><strong>Mobile:</strong> Ketuk dua potongan berturut-turut untuk menukarnya</span>
                </div>
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-blue-400 rounded-full"></div>
                  <span>Angka di pojok kiri menunjukkan posisi saat ini</span>
                </div>
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-blue-400 rounded-full"></div>
                  <span>Susun sesuai urutan yang benar untuk menyelesaikan puzzle</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Puzzle instructions */}
      {question.puzzleData.instructions && (
        <div className="p-4 bg-amber-50 border-l-4 border-amber-400 rounded-r">
          <p className="text-sm text-amber-800">
            <strong>{adminLanguage === 'id' ? 'Instruksi: ' : 'Instructions: '}</strong>
            {question.puzzleData.instructions}
          </p>
        </div>
      )}
      
      {/* Progress indicator */}
      {localPuzzleState && localPuzzleState.pieces.length > 0 && (
        <div className="bg-white border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-gray-700">Progress</span>
            <span className="text-sm text-gray-600">
              {localPuzzleState.pieces.filter(p => p.currentPosition === p.correctPosition).length} / {localPuzzleState.pieces.length}
            </span>
          </div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div 
              className="bg-gradient-to-r from-green-400 to-green-600 h-2 rounded-full transition-all duration-500"
              style={{ 
                width: `${(localPuzzleState.pieces.filter(p => p.currentPosition === p.correctPosition).length / localPuzzleState.pieces.length) * 100}%` 
              }}
            ></div>
          </div>
        </div>
      )}
      
      {/* Puzzle stats */}
      {renderPuzzleStats()}
      
      {/* Puzzle grid */}
      {renderPuzzleGrid()}
      
      {/* Completion message */}
      {localPuzzleState?.isComplete && (
        <div className="p-4 bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-lg">
          <div className="flex items-center space-x-3">
            <div className="flex-shrink-0">
              <div className="w-10 h-10 bg-green-500 rounded-full flex items-center justify-center">
                <Check className="text-white" size={20} />
              </div>
            </div>
            <div className="flex-1">
              <p className="text-green-800 font-semibold text-lg">
                🎉 Selamat! Puzzle berhasil diselesaikan!
              </p>
              <p className="text-sm text-green-700 mt-1">
                Diselesaikan dalam <strong>{localPuzzleState.moves} gerakan</strong> dengan <strong>{localPuzzleState.hints} petunjuk</strong>.
              </p>
            </div>
          </div>
        </div>
      )}
      
      {/* Enhanced instructions for mobile/touch */}
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
        <div className="text-xs text-gray-600 space-y-1">
          <div className="flex items-center justify-between">
            <span className="font-medium">Petunjuk Interaksi:</span>
            <div className="flex items-center space-x-1">
              {selectedPieces.length > 0 && (
                <span className="bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs">
                  {selectedPieces.length === 1 ? 'Pilih potongan kedua' : 'Menukar...'}
                </span>
              )}
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-2 mt-2">
            <div className="flex items-center space-x-2">
              <Move size={14} className="text-gray-400" />
              <span>Seret & lepas (Desktop)</span>
            </div>
            <div className="flex items-center space-x-2">
              <Target size={14} className="text-gray-400" />
              <span>Ketuk 2x untuk tukar (Mobile)</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PuzzleQuestion;