'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, RPGConfig, RPGDecision, RPGOption, RPGConsequence } from '@/types';
import { User, Heart, Brain, MessageCircle, Trophy, ArrowRight, RotateCcw } from 'lucide-react';

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

export default function MiniSimulationRPG({
  question,
  questionIndex,
  onAnswerChange,
  adminLanguage
}: MiniSimulationRPGProps) {
  const config = question.rpgElements as RPGConfig;
  const [currentStep, setCurrentStep] = useState(0);
  const [characterStats, setCharacterStats] = useState(config.character.initialStats);
  const [gameHistory, setGameHistory] = useState<Array<{
    step: number;
    decision: string;
    consequence: RPGConsequence;
    statsChange: any;
  }>>([]);
  const [currentDecision, setCurrentDecision] = useState<RPGDecision | null>(null);
  const [selectedOption, setSelectedOption] = useState<string | null>(null);
  const [showConsequence, setShowConsequence] = useState(false);
  const [gameEnded, setGameEnded] = useState(false);
  const [showResults, setShowResults] = useState(false);
  const [finalResult, setFinalResult] = useState<any>(null);

  useEffect(() => {
    // Initialize first decision
    const firstDecision = config.decisions.find(d => d.step === 0);
    if (firstDecision) {
      setCurrentDecision(firstDecision);
    }
  }, [config]);

  const handleOptionSelect = (optionId: string) => {
    if (showConsequence || gameEnded) return;
    setSelectedOption(optionId);
  };

  const handleConfirmChoice = () => {
    if (!selectedOption || !currentDecision) return;

    const option = currentDecision.options.find(o => o.id === selectedOption);
    const consequence = currentDecision.consequences[selectedOption];

    if (!option || !consequence) return;

    // Apply stat changes
    const newStats = { ...characterStats };
    Object.entries(consequence.statChanges).forEach(([stat, change]) => {
      if (change !== undefined) {
        newStats[stat as keyof typeof newStats] += change;
        // Keep stats within reasonable bounds (0-100)
        newStats[stat as keyof typeof newStats] = Math.max(0, Math.min(100, newStats[stat as keyof typeof newStats]));
      }
    });

    setCharacterStats(newStats);

    // Add to history
    const historyEntry = {
      step: currentStep,
      decision: option.text,
      consequence,
      statsChange: consequence.statChanges
    };
    setGameHistory(prev => [...prev, historyEntry]);

    setShowConsequence(true);

    // Check if game should end
    if (consequence.isEndingPath || currentStep >= config.maxSteps - 1) {
      setTimeout(() => {
        endGame(newStats, historyEntry);
      }, 3000);
    } else {
      // Move to next step
      setTimeout(() => {
        const nextStepNumber = currentStep + 1;
        const nextDecision = config.decisions.find(d => d.step === nextStepNumber);
        
        if (nextDecision) {
          setCurrentStep(nextStepNumber);
          setCurrentDecision(nextDecision);
          setSelectedOption(null);
          setShowConsequence(false);
        } else {
          endGame(newStats, historyEntry);
        }
      }, 3000);
    }
  };

  const endGame = (finalStats: any, lastEntry: any) => {
    setGameEnded(true);
    
    // Calculate final score based on stats
    const totalStats = Object.values(finalStats).reduce((sum: number, stat: any) => sum + stat, 0);
    const averageStats = totalStats / Object.keys(finalStats).length;
    
    // Determine ending type based on final stats and last consequence
    let endingType = lastEntry.consequence.endingType || 'neutral';
    if (averageStats >= 80) endingType = 'success';
    else if (averageStats <= 40) endingType = 'failure';

    const result = {
      character: config.character,
      finalStats,
      gameHistory: [...gameHistory, lastEntry],
      totalSteps: currentStep + 1,
      endingType,
      finalScore: Math.round(averageStats),
      achievements: getAchievements(finalStats, gameHistory.length + 1)
    };

    setFinalResult(result);
    onAnswerChange(result);

    setTimeout(() => {
      setShowResults(true);
    }, 1000);
  };

  const getAchievements = (stats: any, steps: number) => {
    const achievements = [];
    
    if (stats.empathy >= 80) achievements.push('🤝 Master Empati');
    if (stats.leadership >= 80) achievements.push('👑 Pemimpin Hebat');
    if (stats.problemSolving >= 80) achievements.push('🧠 Problem Solver');
    if (stats.communication >= 80) achievements.push('💬 Komunikator Ulung');
    
    if (steps <= 2) achievements.push('⚡ Pengambil Keputusan Cepat');
    if (Object.values(stats).every((stat: any) => stat >= 60)) achievements.push('🌟 Karakter Seimbang');
    
    return achievements;
  };

  const resetGame = () => {
    setCurrentStep(0);
    setCharacterStats(config.character.initialStats);
    setGameHistory([]);
    setSelectedOption(null);
    setShowConsequence(false);
    setGameEnded(false);
    setFinalResult(null);
    
    const firstDecision = config.decisions.find(d => d.step === 0);
    if (firstDecision) {
      setCurrentDecision(firstDecision);
    }
  };

  const getStatIcon = (statName: string) => {
    switch (statName) {
      case 'empathy': return <Heart className="w-4 h-4" />;
      case 'leadership': return <Trophy className="w-4 h-4" />;
      case 'problemSolving': return <Brain className="w-4 h-4" />;
      case 'communication': return <MessageCircle className="w-4 h-4" />;
      default: return <User className="w-4 h-4" />;
    }
  };

  const getStatColor = (value: number) => {
    if (value >= 80) return 'text-green-600 bg-green-100';
    if (value >= 60) return 'text-blue-600 bg-blue-100';
    if (value >= 40) return 'text-yellow-600 bg-yellow-100';
    return 'text-red-600 bg-red-100';
  };

  const getStatName = (key: string) => {
    const names: { [key: string]: string } = {
      empathy: 'Empati',
      leadership: 'Kepemimpinan',
      problemSolving: 'Problem Solving',
      communication: 'Komunikasi'
    };
    return names[key] || key;
  };

  if (gameEnded && finalResult) {
    return (
      <Card className="w-full max-w-3xl mx-auto">
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <span>🎮 Hasil Simulasi RPG</span>
            <Badge className={`
              ${finalResult.endingType === 'success' ? 'bg-green-500' : 
                finalResult.endingType === 'failure' ? 'bg-red-500' : 'bg-blue-500'}
            `}>
              {finalResult.endingType === 'success' ? '🏆 Sukses' : 
               finalResult.endingType === 'failure' ? '💔 Gagal' : '⚖️ Netral'}
            </Badge>
          </CardTitle>
        </CardHeader>

        <CardContent className="space-y-6">
          {/* Final Stats */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {Object.entries(finalResult.finalStats).map(([key, value]) => (
              <div key={key} className={`p-3 rounded-lg ${getStatColor(value as number)}`}>
                <div className="flex items-center gap-2 mb-1">
                  {getStatIcon(key)}
                  <span className="text-sm font-medium">{getStatName(key)}</span>
                </div>
                <div className="text-lg font-bold">{value as number}</div>
                <div className="text-xs opacity-75">
                  {gameHistory.length > 0 && (
                    <span>
                      {(() => {
                        const total = gameHistory.reduce((acc, entry) => {
                          Object.entries(entry.statsChange).forEach(([stat, change]) => {
                            if (stat === key && change !== undefined && typeof change === 'number') {
                              acc += change;
                            }
                          });
                          return acc;
                        }, 0);
                        return total > 0 ? `+${total}` : total < 0 ? `${total}` : '0';
                      })()}
                    </span>
                  )}
                </div>
              </div>
            ))}
          </div>

          {/* Achievements */}
          {finalResult.achievements.length > 0 && (
            <div>
              <h3 className="font-semibold mb-2">🏅 Pencapaian:</h3>
              <div className="flex flex-wrap gap-2">
                {finalResult.achievements.map((achievement: string, index: number) => (
                  <Badge key={index} variant="outline" className="bg-yellow-50 border-yellow-200">
                    {achievement}
                  </Badge>
                ))}
              </div>
            </div>
          )}

          {/* Game History */}
          <div>
            <h3 className="font-semibold mb-2">📖 Perjalanan Cerita:</h3>
            <div className="space-y-3">
              {finalResult.gameHistory.map((entry: any, index: number) => (
                <div key={index} className="p-3 bg-gray-50 rounded-lg border-l-4 border-blue-500">
                  <div className="flex items-start gap-2">
                    <Badge variant="outline" className="mt-1">Langkah {entry.step + 1}</Badge>
                    <div className="flex-1">
                      <p className="font-medium text-sm">{entry.decision}</p>
                      <p className="text-sm text-gray-600 mt-1">{entry.consequence.message}</p>
                      {Object.keys(entry.statsChange).length > 0 && (
                        <div className="flex gap-2 mt-2">
                          {Object.entries(entry.statsChange).map(([stat, change]) => 
                            change !== undefined && change !== 0 && typeof change === 'number' ? (
                              <span key={stat} className={`text-xs px-2 py-1 rounded ${
                                change > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                              }`}>
                                {getStatName(stat)} {change > 0 ? '+' : ''}{change}
                              </span>
                            ) : null
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Final Score */}
          <div className="text-center p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border">
            <h3 className="font-bold text-lg mb-2">Skor Akhir</h3>
            <div className="text-3xl font-bold text-blue-600">{finalResult.finalScore}/100</div>
            <p className="text-sm text-gray-600 mt-1">
              Berdasarkan rata-rata semua atribut karakter
            </p>
          </div>

          <div className="flex justify-center">
            <Button onClick={resetGame} variant="outline" className="flex items-center gap-2">
              <RotateCcw className="w-4 h-4" />
              Main Lagi
            </Button>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full max-w-3xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span>🎮 Mini Simulation RPG</span>
          <Badge variant="outline">
            Langkah {currentStep + 1}/{config.maxSteps}
          </Badge>
        </CardTitle>
        
        {/* Character Info */}
        <div className="bg-gradient-to-r from-blue-50 to-purple-50 p-4 rounded-lg">
          <div className="flex items-center gap-3 mb-3">
            {config.character.avatar && (
              <img 
                src={config.character.avatar} 
                alt={config.character.name}
                className="w-12 h-12 rounded-full border-2 border-white shadow"
              />
            )}
            <div>
              <h3 className="font-bold">{config.character.name}</h3>
              <p className="text-sm text-gray-600">{config.character.role}</p>
            </div>
          </div>
          
          {/* Current Stats */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
            {Object.entries(characterStats).map(([key, value]) => (
              <div key={key} className="flex items-center gap-1 text-sm">
                {getStatIcon(key)}
                <span className="truncate">{getStatName(key)}</span>
                <Badge variant="outline" className="ml-auto">
                  {value}
                </Badge>
              </div>
            ))}
          </div>
        </div>
      </CardHeader>

      <CardContent className="space-y-6">
        {/* Scenario */}
        <div className="p-4 bg-yellow-50 border-l-4 border-yellow-400 rounded">
          <h3 className="font-semibold mb-2">📋 Skenario:</h3>
          <p>{config.scenario}</p>
        </div>

        {/* Current Decision */}
        {currentDecision && !showConsequence && (
          <div>
            <h3 className="font-semibold mb-3">🤔 Situasi:</h3>
            <p className="mb-4 p-3 bg-gray-50 rounded border">{currentDecision.situation}</p>
            
            <h4 className="font-medium mb-3">Pilih tindakan Anda:</h4>
            <div className="space-y-3">
              {currentDecision.options.map((option) => (
                <Button
                  key={option.id}
                  variant={selectedOption === option.id ? "default" : "outline"}
                  className={`
                    w-full text-left p-4 h-auto justify-start
                    ${selectedOption === option.id ? 'bg-blue-600 hover:bg-blue-700' : 'hover:bg-blue-50'}
                    ${option.difficulty === 'hard' ? 'border-red-200' : 
                      option.difficulty === 'medium' ? 'border-yellow-200' : 'border-green-200'}
                  `}
                  onClick={() => handleOptionSelect(option.id)}
                >
                  <div className="flex items-start gap-3 w-full">
                    {option.icon && <span className="text-xl">{option.icon}</span>}
                    <div className="flex-1">
                      <p className="font-medium">{option.text}</p>
                      <div className="flex items-center gap-2 mt-1">
                        <Badge 
                          variant="outline" 
                          className={`text-xs ${
                            option.difficulty === 'hard' ? 'border-red-300 text-red-600' :
                            option.difficulty === 'medium' ? 'border-yellow-300 text-yellow-600' :
                            'border-green-300 text-green-600'
                          }`}
                        >
                          {option.difficulty === 'easy' ? '😊 Mudah' : 
                           option.difficulty === 'medium' ? '😐 Sedang' : '😰 Sulit'}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </Button>
              ))}
            </div>

            {selectedOption && (
              <div className="flex justify-center mt-4">
                <Button 
                  onClick={handleConfirmChoice}
                  className="bg-green-600 hover:bg-green-700 flex items-center gap-2"
                >
                  Konfirmasi Pilihan
                  <ArrowRight className="w-4 h-4" />
                </Button>
              </div>
            )}
          </div>
        )}

        {/* Consequence Display */}
        {showConsequence && selectedOption && currentDecision && (
          <div className="space-y-4">
            <div className="p-4 bg-blue-50 border-l-4 border-blue-400 rounded">
              <h3 className="font-semibold mb-2">📢 Konsekuensi:</h3>
              <p>{currentDecision.consequences[selectedOption].message}</p>
            </div>

            {/* Stat Changes */}
            {Object.keys(currentDecision.consequences[selectedOption].statChanges).length > 0 && (
              <div className="p-4 bg-gray-50 rounded">
                <h4 className="font-medium mb-2">📊 Perubahan Atribut:</h4>
                <div className="grid grid-cols-2 gap-2">
                  {Object.entries(currentDecision.consequences[selectedOption].statChanges).map(([stat, change]) => (
                    change !== undefined && change !== 0 && (
                      <div key={stat} className={`flex items-center gap-2 p-2 rounded ${
                        (change as number) > 0 ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                      }`}>
                        {getStatIcon(stat)}
                        <span className="text-sm">{getStatName(stat)}</span>
                        <span className="font-bold ml-auto">
                          {(change as number) > 0 ? '+' : ''}{change}
                        </span>
                      </div>
                    )
                  ))}
                </div>
              </div>
            )}

            <div className="text-center text-sm text-gray-500">
              {currentDecision.consequences[selectedOption].isEndingPath ? 
                'Cerita akan berakhir...' : 
                'Melanjutkan ke langkah berikutnya...'}
            </div>
          </div>
        )}

        {/* Progress Indicator */}
        <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: `${((currentStep + 1) / config.maxSteps) * 100}%` }}
          />
        </div>
      </CardContent>
    </Card>
  );
}