import React, { useState, useEffect, useCallback, useRef } from 'react';
import { TriviaQuestion, Decade, Category, Difficulty, HighScoreRecord, GameMode } from '../types';
import { VinylSpinner, VinylSpinnerRef } from './VinylSpinner';
import { QuestionCard } from './QuestionCard';
import { HostNarrator } from './HostNarrator';
import { sound } from '../utils/audio';
import { getLocalTriviaQuestion } from '../data/triviaService';
import { Flame, Trophy, Play, RotateCcw, ArrowRight, Sparkles, CheckCircle, Zap, RefreshCw } from 'lucide-react';

interface SoloPlayViewProps {
  onSaveScore: (record: HighScoreRecord) => void;
  onSwitchMode?: (mode: GameMode) => void;
}

export const SoloPlayView: React.FC<SoloPlayViewProps> = ({ onSaveScore, onSwitchMode }) => {
  const spinnerRef = useRef<VinylSpinnerRef>(null);
  const [playerName, setPlayerName] = useState<string>('Jugador Retro');
  const [difficulty, setDifficulty] = useState<Difficulty>('Fácil');
  const [gameStarted, setGameStarted] = useState<boolean>(false);
  const [gameOver, setGameOver] = useState<boolean>(false);

  const [score, setScore] = useState<number>(0);
  const [streak, setStreak] = useState<number>(0);
  const [correctAnswers, setCorrectAnswers] = useState<number>(0);
  const [totalQuestions, setTotalQuestions] = useState<number>(0);

  const [currentDecade, setCurrentDecade] = useState<Decade | null>(null);
  const [currentCategory, setCurrentCategory] = useState<Category | null>(null);
  const [currentQuestion, setCurrentQuestion] = useState<TriviaQuestion | null>(null);
  
  const [isLoadingQuestion, setIsLoadingQuestion] = useState<boolean>(false);
  const [isSpinning, setIsSpinning] = useState<boolean>(false);
  const [historyQuestions, setHistoryQuestions] = useState<string[]>([]);
  const [showNextButton, setShowNextButton] = useState<boolean>(false);

  // Fetch question from local high-speed JSON database (hosting-ready, no API keys required)
  const fetchQuestion = useCallback((decade?: Decade, category?: Category) => {
    setIsLoadingQuestion(true);
    setShowNextButton(false);

    const targetDecade = decade || currentDecade || '80';
    const targetCategory = category || currentCategory || 'Música';

    // Simulate instant retro radio retrieval
    setTimeout(() => {
      try {
        const questionData = getLocalTriviaQuestion({
          decade: targetDecade,
          category: targetCategory,
          difficulty: difficulty,
          alreadyAsked: historyQuestions
        });

        if (questionData) {
          setCurrentQuestion(questionData);
          setCurrentDecade(questionData.decade);
          setCurrentCategory(questionData.category);
          setHistoryQuestions(prev => [...prev.slice(-30), questionData.question]);
        }
      } catch (err) {
        console.error("Failed to load local trivia question:", err);
      } finally {
        setIsLoadingQuestion(false);
      }
    }, 150);
  }, [currentDecade, currentCategory, difficulty, historyQuestions]);

  const handleStartGame = () => {
    sound.playClick();
    setGameStarted(true);
    setGameOver(false);
    setScore(0);
    setStreak(0);
    setCorrectAnswers(0);
    setTotalQuestions(0);
    setCurrentQuestion(null);
    setCurrentDecade(null);
    setCurrentCategory(null);
  };

  const handleSpinResult = (decade: Decade, category: Category) => {
    setCurrentDecade(decade);
    setCurrentCategory(category);
    fetchQuestion(decade, category);
  };

  const handleAnswerQuestion = (selectedIndex: number, isCorrect: boolean, timeSpentSeconds: number) => {
    setTotalQuestions(prev => prev + 1);

    if (isCorrect) {
      const newStreak = streak + 1;
      setStreak(newStreak);
      setCorrectAnswers(prev => prev + 1);

      // Score calculation: Base 100 pts + streak bonus + time bonus
      const speedBonus = Math.max(0, (20 - timeSpentSeconds) * 5);
      const streakMultiplier = 1 + Math.min(newStreak * 0.2, 2.0);
      const difficultyBonus = difficulty === 'Experto' ? 50 : 0;

      const addedPoints = Math.round((100 + speedBonus + difficultyBonus) * streakMultiplier);
      setScore(prev => prev + addedPoints);
    } else {
      setStreak(0);
    }

    setShowNextButton(true);
  };

  const handleNextQuestion = () => {
    sound.playClick();
    fetchQuestion();
  };

  const handleEndGame = () => {
    sound.playVictory();
    setGameOver(true);

    if (score > 0) {
      onSaveScore({
        id: Date.now().toString(),
        playerName: playerName || 'Jugador Retro',
        score,
        streak,
        decade: currentDecade || 'Mezclado',
        difficulty,
        date: new Date().toLocaleDateString('es-ES')
      });
    }
  };

  if (!gameStarted) {
    return (
      <div className="w-full max-w-xl mx-auto py-6 px-4">
        <div className="bg-[#1a1724] border-2 border-amber-500/40 rounded-3xl p-6 shadow-2xl text-center">
          <div className="w-16 h-16 rounded-2xl bg-amber-500/10 border border-amber-500/40 text-amber-400 mx-auto flex items-center justify-center text-3xl mb-4">
            🕹️
          </div>
          <h2 className="font-righteous text-2xl sm:text-3xl text-amber-300 mb-3">MODO UN SOLO JUGADOR</h2>
          <p className="text-base sm:text-lg text-amber-100/90 font-medium mb-5 leading-relaxed">
            Demuestra tus conocimientos en una carrera nostálgica.<br />
            Mantén tu racha de aciertos para multiplicar tus puntos.
          </p>

          {/* Mode Selection Options directly below description */}
          <div className="flex items-center justify-center gap-2 mb-6 bg-[#121016] p-1.5 rounded-xl border border-amber-500/30 max-w-sm mx-auto">
            <button
              type="button"
              onClick={() => {
                sound.playClick();
                if (onSwitchMode) onSwitchMode('Solo');
              }}
              className="flex-1 py-2 px-3 rounded-lg text-xs font-bold bg-gradient-to-r from-amber-500 to-amber-600 text-black shadow-md shadow-amber-500/30"
            >
              🕹️ Un Solo Jugador
            </button>
            <button
              type="button"
              onClick={() => {
                sound.playClick();
                if (onSwitchMode) onSwitchMode('Competencia');
              }}
              className="flex-1 py-2 px-3 rounded-lg text-xs font-bold text-amber-200/70 hover:text-amber-200 hover:bg-amber-500/10 transition-all"
            >
              🏆 Competencia
            </button>
          </div>

          {/* Config Controls */}
          <div className="space-y-4 text-left bg-zinc-900/60 p-4 rounded-2xl border border-amber-500/20 mb-6">
            <div>
              <label className="block text-xs font-bold text-amber-300/80 mb-1">Tu Nombre o Nombre de Agente:</label>
              <input
                type="text"
                value={playerName}
                onChange={e => setPlayerName(e.target.value)}
                maxLength={20}
                className="w-full px-3.5 py-2.5 rounded-xl bg-[#121016] border border-amber-500/40 text-amber-100 text-sm focus:outline-none focus:border-amber-400"
              />
            </div>

            <div>
              <label className="block text-xs font-bold text-amber-300/80 mb-1">Dificultad de la Trivia:</label>
              <div className="grid grid-cols-2 gap-2">
                <button
                  onClick={() => {
                    sound.playClick();
                    setDifficulty('Fácil');
                  }}
                  className={`py-2 rounded-xl border text-xs font-bold transition-all ${
                    difficulty === 'Fácil'
                      ? 'bg-teal-500/20 border-teal-400 text-teal-300 ring-2 ring-teal-500/30'
                      : 'bg-zinc-800 border-zinc-700 text-zinc-400'
                  }`}
                >
                  🟢 Nivel FÁCIL
                </button>
                <button
                  onClick={() => {
                    sound.playClick();
                    setDifficulty('Experto');
                  }}
                  className={`py-2 rounded-xl border text-xs font-bold transition-all ${
                    difficulty === 'Experto'
                      ? 'bg-purple-500/20 border-purple-400 text-purple-300 ring-2 ring-purple-500/30'
                      : 'bg-zinc-800 border-zinc-700 text-zinc-400'
                  }`}
                >
                  🟣 Nivel EXPERTO
                </button>
              </div>
            </div>
          </div>

          <button
            onClick={handleStartGame}
            className="w-full py-3.5 rounded-2xl bg-gradient-to-r from-amber-500 via-orange-500 to-red-500 hover:from-amber-400 hover:to-red-400 text-black font-righteous text-lg tracking-wider shadow-lg shadow-amber-500/20 hover:scale-[1.02] active:scale-[0.98] transition-all flex items-center justify-center gap-2"
          >
            <Play className="w-5 h-5 fill-black" />
            <span>INICIAR DESAFÍO SOLO</span>
          </button>
        </div>
      </div>
    );
  }

  if (gameOver) {
    return (
      <div className="w-full max-w-lg mx-auto py-6 px-4">
        <div className="bg-[#1a1724] border-2 border-amber-500/40 rounded-3xl p-6 shadow-2xl text-center">
          <div className="w-16 h-16 rounded-full bg-amber-500/20 border-2 border-amber-400 text-amber-400 mx-auto flex items-center justify-center text-3xl mb-4 animate-bounce">
            🏆
          </div>
          <h2 className="font-righteous text-2xl text-amber-300 mb-1">¡FIN DE LA SESIÓN!</h2>
          <p className="text-xs text-amber-200/70 mb-6">Resumen temporal de {playerName}</p>

          <div className="grid grid-cols-2 gap-3 mb-6">
            <div className="bg-zinc-900/80 p-3.5 rounded-2xl border border-amber-500/20">
              <span className="text-[10px] font-bold text-amber-300/60 uppercase">PUNTUACIÓN FINAL</span>
              <div className="font-pixel text-2xl text-amber-400 mt-1">{score}</div>
            </div>
            <div className="bg-zinc-900/80 p-3.5 rounded-2xl border border-amber-500/20">
              <span className="text-[10px] font-bold text-amber-300/60 uppercase">MEJOR RACHA</span>
              <div className="font-pixel text-2xl text-orange-400 mt-1">{streak}🔥</div>
            </div>
            <div className="bg-zinc-900/80 p-3.5 rounded-2xl border border-amber-500/20">
              <span className="text-[10px] font-bold text-amber-300/60 uppercase">ACIERTOS</span>
              <div className="font-pixel text-lg text-emerald-400 mt-1">{correctAnswers} / {totalQuestions}</div>
            </div>
            <div className="bg-zinc-900/80 p-3.5 rounded-2xl border border-amber-500/20">
              <span className="text-[10px] font-bold text-amber-300/60 uppercase">DIFICULTAD</span>
              <div className="font-bold text-sm text-purple-300 mt-1">{difficulty}</div>
            </div>
          </div>

          <div className="flex gap-2">
            <button
              onClick={handleStartGame}
              className="flex-1 py-3 rounded-xl bg-amber-500 hover:bg-amber-400 text-black font-righteous text-sm shadow-md transition-all flex items-center justify-center gap-1.5"
            >
              <RotateCcw className="w-4 h-4" />
              <span>JUGAR DE NUEVO</span>
            </button>
            <button
              onClick={() => setGameStarted(false)}
              className="py-3 px-4 rounded-xl bg-zinc-800 hover:bg-zinc-700 text-amber-200 font-bold text-sm border border-zinc-700 transition-all"
            >
              MENÚ
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full max-w-4xl mx-auto px-2 py-4 space-y-6">
      {/* Live Solo Score HUD */}
      <div className="bg-[#181520] border border-amber-500/30 rounded-2xl p-3 sm:p-4 flex flex-wrap items-center justify-between gap-3 shadow-xl">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-amber-500/20 border border-amber-400 flex items-center justify-center text-xl">
            🕹️
          </div>
          <div>
            <h3 className="font-bold text-sm text-amber-100">{playerName}</h3>
            <span className="text-[10px] text-amber-300/70 uppercase">Modo Solo • Nivel {difficulty}</span>
          </div>
        </div>

        <div className="flex items-center gap-4">
          <div className="text-right">
            <span className="text-[9px] font-bold text-amber-300/60 uppercase block">Racha</span>
            <div className="flex items-center gap-1 font-pixel text-sm text-orange-400">
              <Flame className="w-4 h-4" />
              <span>{streak}</span>
            </div>
          </div>

          <div className="text-right">
            <span className="text-[9px] font-bold text-amber-300/60 uppercase block">Puntos</span>
            <div className="font-pixel text-xl text-amber-400">
              {score}
            </div>
          </div>

          <button
            onClick={handleEndGame}
            className="px-3 py-1.5 rounded-lg bg-red-950/60 hover:bg-red-900 border border-red-500/40 text-red-300 text-xs font-bold transition-all"
          >
            Finalizar
          </button>
        </div>
      </div>

      {/* Host Voice Commentary */}
      <HostNarrator
        message={currentQuestion?.host_flavor_text || "¡Gira la rueda temporal para lanzar tu siguiente desafío retro!"}
        isThinking={isLoadingQuestion}
      />

      {/* Main Wheel Spinner & Question Area */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
        {/* Left Column: Vinyl Wheel Spinner */}
        <div className="lg:col-span-5 bg-[#181522] border border-amber-500/20 rounded-2xl p-3 shadow-xl flex flex-col items-center">
          <VinylSpinner
            ref={spinnerRef}
            onSpinResult={handleSpinResult}
            isSpinning={isSpinning}
            setIsSpinning={setIsSpinning}
            selectedDecade={currentDecade}
            selectedCategory={currentCategory}
          />
        </div>

        {/* Right Column: Question Card Display & Integrated Action Button */}
        <div className="lg:col-span-7 space-y-4">
          {currentQuestion ? (
            <>
              <QuestionCard
                question={currentQuestion}
                onAnswer={handleAnswerQuestion}
                timerDurationSeconds={20}
                isLoading={isLoadingQuestion}
              />

              {/* Next Question Action Button */}
              {showNextButton && (
                <button
                  onClick={() => {
                    sound.playClick();
                    setCurrentQuestion(null);
                    setShowNextButton(false);
                    spinnerRef.current?.spin();
                  }}
                  disabled={isSpinning || isLoadingQuestion}
                  className={`w-full py-4 rounded-2xl font-righteous text-lg tracking-wider transition-all shadow-xl flex items-center justify-center gap-2 ${
                    isSpinning || isLoadingQuestion
                      ? 'bg-zinc-800 border border-amber-500/30 text-amber-300/80 cursor-wait'
                      : 'bg-gradient-to-r from-amber-500 via-orange-500 to-red-500 hover:from-amber-400 hover:to-red-400 text-black shadow-amber-500/30 hover:scale-[1.01] active:scale-[0.98] animate-bounce'
                  }`}
                >
                  {isSpinning || isLoadingQuestion ? (
                    <>
                      <RefreshCw className="w-5 h-5 animate-spin text-amber-400" />
                      <span>GIRANDO RUEDA TEMPORAL...</span>
                    </>
                  ) : (
                    <>
                      <span>SIGUIENTE PREGUNTA RETRO →</span>
                    </>
                  )}
                </button>
              )}
            </>
          ) : (
            <div className="bg-[#181522] border border-amber-500/20 rounded-2xl p-6 sm:p-8 text-center min-h-[300px] flex flex-col items-center justify-center space-y-5">
              <div>
                <Sparkles className="w-12 h-12 text-amber-400 mx-auto mb-3 animate-pulse" />
                <h3 className="font-righteous text-xl text-amber-300">¡Gira la Rueda Temporal!</h3>
                <p className="text-xs sm:text-sm text-amber-200/70 max-w-sm mx-auto mt-1 leading-relaxed">
                  Haz clic en el botón inferior para lanzar la rueda temporal, calcular tu coordenada retro y desplegar tu primera pregunta.
                </p>
              </div>

              {/* Primary Action Button (Initial Spin / Game Start) */}
              <button
                onClick={() => {
                  sound.playClick();
                  spinnerRef.current?.spin();
                }}
                disabled={isSpinning || isLoadingQuestion}
                className={`w-full max-w-sm py-4 rounded-2xl font-righteous text-lg tracking-wider transition-all shadow-xl flex items-center justify-center gap-2.5 ${
                  isSpinning || isLoadingQuestion
                    ? 'bg-zinc-800 border border-amber-500/30 text-amber-300/80 cursor-wait'
                    : 'bg-gradient-to-r from-amber-500 via-orange-500 to-red-500 hover:from-amber-400 hover:to-red-400 text-black shadow-amber-500/30 hover:scale-[1.02] active:scale-[0.98] animate-pulse'
                }`}
              >
                {isSpinning || isLoadingQuestion ? (
                  <>
                    <RefreshCw className="w-5 h-5 animate-spin text-amber-400" />
                    <span>GIRANDO RUEDA TEMPORAL...</span>
                  </>
                ) : (
                  <>
                    <RefreshCw className="w-5 h-5" />
                    <span>¡GIRA LA RUEDA TEMPORAL!</span>
                  </>
                )}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
