'use client';

import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { InteractiveQuestion, VisualMatchingConfig, MatchingPair } from '@/types';
import { CheckCircle, XCircle, RotateCcw, Eye } from 'lucide-react';

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

export default function PuzzleGambarIconMatch({
  question,
  questionIndex,
  onAnswerChange,
  adminLanguage
}: PuzzleGambarIconMatchProps) {
  const config = question.visualElements as VisualMatchingConfig;
  const [matches, setMatches] = useState<{ [key: string]: string }>({});
  const [draggedItem, setDraggedItem] = useState<string | null>(null);
  const [attempts, setAttempts] = useState(0);
  const [showHints, setShowHints] = useState(false);
  const [feedback, setFeedback] = useState<{ [key: string]: boolean }>({});
  const [showResults, setShowResults] = useState(false);

  useEffect(() => {
    // Initialize empty matches
    const initialMatches: { [key: string]: string } = {};
    config.matchingPairs.forEach(pair => {
      initialMatches[pair.leftItem.id] = '';
    });
    setMatches(initialMatches);
  }, [config]);

  const handleDragStart = (e: React.DragEvent, itemId: string) => {
    setDraggedItem(itemId);
    e.dataTransfer.effectAllowed = 'move';
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e: React.DragEvent, leftItemId: string) => {
    e.preventDefault();
    if (draggedItem) {
      const newMatches = { ...matches };
      
      // Remove previous match for this right item
      Object.keys(newMatches).forEach(key => {
        if (newMatches[key] === draggedItem) {
          newMatches[key] = '';
        }
      });
      
      // Set new match
      newMatches[leftItemId] = draggedItem;
      setMatches(newMatches);
      setDraggedItem(null);
    }
  };

  const handleDirectMatch = (leftItemId: string, rightItemId: string) => {
    const newMatches = { ...matches };
    
    // Remove previous match for this right item
    Object.keys(newMatches).forEach(key => {
      if (newMatches[key] === rightItemId) {
        newMatches[key] = '';
      }
    });
    
    // Toggle match
    if (newMatches[leftItemId] === rightItemId) {
      newMatches[leftItemId] = '';
    } else {
      newMatches[leftItemId] = rightItemId;
    }
    
    setMatches(newMatches);
  };

  const checkAnswers = () => {
    const newFeedback: { [key: string]: boolean } = {};
    let correctCount = 0;

    config.matchingPairs.forEach(pair => {
      const isCorrect = matches[pair.leftItem.id] === pair.rightItem.id;
      newFeedback[pair.leftItem.id] = isCorrect;
      if (isCorrect) correctCount++;
    });

    setFeedback(newFeedback);
    setAttempts(prev => prev + 1);

    const result = {
      matches,
      correctCount,
      totalPairs: config.matchingPairs.length,
      attempts: attempts + 1,
      score: (correctCount / config.matchingPairs.length) * 100
    };

    onAnswerChange(result);

    if (correctCount === config.matchingPairs.length) {
      setShowResults(true);
    }
  };

  const resetMatches = () => {
    const resetMatches: { [key: string]: string } = {};
    config.matchingPairs.forEach(pair => {
      resetMatches[pair.leftItem.id] = '';
    });
    setMatches(resetMatches);
    setFeedback({});
  };

  const toggleHints = () => {
    setShowHints(!showHints);
  };

  const getRightItems = () => {
    return config.matchingPairs.map(pair => pair.rightItem);
  };

  const getMatchedRightItem = (leftItemId: string) => {
    const rightItemId = matches[leftItemId];
    return config.matchingPairs.find(pair => pair.rightItem.id === rightItemId)?.rightItem;
  };

  const isAllMatched = () => {
    return Object.values(matches).every(match => match !== '');
  };

  const getAvailableRightItems = () => {
    const matchedIds = Object.values(matches).filter(id => id !== '');
    return getRightItems().filter(item => !matchedIds.includes(item.id));
  };

  return (
    <Card className="w-full max-w-4xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span>🧩 Puzzle Gambar / Icon Match</span>
          <div className="flex gap-2">
            <Badge variant="outline">
              Percobaan: {attempts}/{config.maxAttempts}
            </Badge>
            {config.showHints && (
              <Button
                variant="outline"
                size="sm"
                onClick={toggleHints}
                className="flex items-center gap-1"
              >
                <Eye className="w-4 h-4" />
                {showHints ? 'Sembunyikan' : 'Tampilkan'} Petunjuk
              </Button>
            )}
          </div>
        </CardTitle>
        <p className="text-sm text-muted-foreground">
          {question.content.question}
        </p>
        {question.content.instructions && (
          <p className="text-sm text-blue-600 bg-blue-50 p-2 rounded">
            💡 {question.content.instructions}
          </p>
        )}
      </CardHeader>

      <CardContent className="space-y-6">
        {/* Matching Area */}
        <div className={`grid gap-4 ${
          config.visualStyle === 'grid' ? 'md:grid-cols-2' : 'grid-cols-1'
        }`}>
          {/* Left Items (Drop Zones) */}
          <div className="space-y-3">
            <h3 className="font-semibold text-sm text-gray-600">
              Pasangkan dengan item yang sesuai:
            </h3>
            {config.matchingPairs.map((pair) => (
              <div
                key={pair.leftItem.id}
                className={`
                  relative p-4 border-2 border-dashed rounded-lg min-h-[80px]
                  flex items-center justify-between transition-all duration-200
                  ${draggedItem ? 'border-blue-300 bg-blue-50' : 'border-gray-300'}
                  ${feedback[pair.leftItem.id] === true ? 'border-green-500 bg-green-50' : ''}
                  ${feedback[pair.leftItem.id] === false ? 'border-red-500 bg-red-50' : ''}
                `}
                onDragOver={handleDragOver}
                onDrop={(e) => handleDrop(e, pair.leftItem.id)}
              >
                {/* Left Item */}
                <div className="flex items-center gap-3">
                  {pair.leftItem.image && (
                    <img 
                      src={pair.leftItem.image} 
                      alt={pair.leftItem.content}
                      className="w-12 h-12 object-cover rounded"
                    />
                  )}
                  {pair.leftItem.icon && (
                    <span className="text-2xl">{pair.leftItem.icon}</span>
                  )}
                  <span className="font-medium">{pair.leftItem.content}</span>
                </div>

                {/* Matched Right Item */}
                {getMatchedRightItem(pair.leftItem.id) && (
                  <div className="flex items-center gap-2 bg-white p-2 rounded border">
                    {getMatchedRightItem(pair.leftItem.id)?.image && (
                      <img 
                        src={getMatchedRightItem(pair.leftItem.id)?.image} 
                        alt={getMatchedRightItem(pair.leftItem.id)?.content}
                        className="w-8 h-8 object-cover rounded"
                      />
                    )}
                    {getMatchedRightItem(pair.leftItem.id)?.icon && (
                      <span className="text-lg">{getMatchedRightItem(pair.leftItem.id)?.icon}</span>
                    )}
                    <span className="text-sm">{getMatchedRightItem(pair.leftItem.id)?.content}</span>
                  </div>
                )}

                {/* Feedback Icons */}
                {feedback[pair.leftItem.id] === true && (
                  <CheckCircle className="w-6 h-6 text-green-500 absolute -top-2 -right-2" />
                )}
                {feedback[pair.leftItem.id] === false && (
                  <XCircle className="w-6 h-6 text-red-500 absolute -top-2 -right-2" />
                )}

                {/* Hint */}
                {showHints && (
                  <div className="absolute -bottom-8 left-0 text-xs text-blue-600 bg-blue-100 px-2 py-1 rounded">
                    Cocokkan dengan: {pair.rightItem.content}
                  </div>
                )}
              </div>
            ))}
          </div>

          {/* Right Items (Draggable) */}
          <div className="space-y-3">
            <h3 className="font-semibold text-sm text-gray-600">
              Pilihan yang tersedia:
            </h3>
            <div className="grid grid-cols-2 gap-2">
              {getAvailableRightItems().map((item) => (
                <div
                  key={item.id}
                  draggable={config.allowDragDrop}
                  onDragStart={(e) => handleDragStart(e, item.id)}
                  className={`
                    p-3 border rounded-lg cursor-pointer transition-all duration-200
                    flex flex-col items-center gap-2 text-center
                    ${config.allowDragDrop ? 'hover:shadow-md hover:scale-105' : ''}
                    ${draggedItem === item.id ? 'opacity-50 scale-95' : ''}
                    bg-white border-gray-200 hover:border-blue-300
                  `}
                  onClick={() => {
                    if (!config.allowDragDrop) {
                      // Find which left item to match with (simple click mode)
                      const unmatched = config.matchingPairs.find(pair => 
                        matches[pair.leftItem.id] === ''
                      );
                      if (unmatched) {
                        handleDirectMatch(unmatched.leftItem.id, item.id);
                      }
                    }
                  }}
                >
                  {item.image && (
                    <img 
                      src={item.image} 
                      alt={item.content}
                      className="w-10 h-10 object-cover rounded"
                    />
                  )}
                  {item.icon && (
                    <span className="text-xl">{item.icon}</span>
                  )}
                  <span className="text-sm font-medium">{item.content}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex justify-between items-center pt-4 border-t">
          <Button
            variant="outline"
            onClick={resetMatches}
            className="flex items-center gap-2"
            disabled={showResults}
          >
            <RotateCcw className="w-4 h-4" />
            Reset
          </Button>

          <div className="flex gap-2">
            <Button
              onClick={checkAnswers}
              disabled={!isAllMatched() || showResults || attempts >= config.maxAttempts}
              className="bg-blue-600 hover:bg-blue-700"
            >
              {attempts === 0 ? 'Periksa Jawaban' : 'Coba Lagi'}
            </Button>
          </div>
        </div>

        {/* Progress Indicator */}
        <div className="text-center text-sm text-gray-500">
          {Object.values(matches).filter(m => m !== '').length} / {config.matchingPairs.length} pasangan selesai
        </div>
      </CardContent>
    </Card>
  );
}