import React, { useState, useEffect } from 'react';
import { TriviaQuestion } from '../types';
import { Music, Tv, Trophy, Boxes, Clock, CheckCircle2, XCircle, Sparkles } from 'lucide-react';
import { sound } from '../utils/audio';

interface QuestionCardProps {
  question: TriviaQuestion;
  onAnswer: (selectedIndex: number, isCorrect: boolean, timeSpentSeconds: number) => void;
  timerDurationSeconds?: number;
  isLoading?: boolean;
}

export const QuestionCard: React.FC<QuestionCardProps> = ({
  question,
  onAnswer,
  timerDurationSeconds = 20,
  isLoading = false,
}) => {
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
  const [isAnswered, setIsAnswered] = useState<boolean>(false);
  const [timeLeft, setTimeLeft] = useState<number>(timerDurationSeconds);

  useEffect(() => {
    setSelectedIndex(null);
    setIsAnswered(false);
    setTimeLeft(timerDurationSeconds);
  }, [question, timerDurationSeconds]);

  // Countdown timer effect
  useEffect(() => {
    if (isAnswered || isLoading) return;

    if (timeLeft <= 0) {
      // Time up! Auto handle wrong answer
      setIsAnswered(true);
      sound.playIncorrect();
      onAnswer(-1, false, timerDurationSeconds);
      return;
    }

    const timer = setInterval(() => {
      setTimeLeft(prev => {
        if (prev <= 5 && prev > 1) sound.playTimerTick();
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [timeLeft, isAnswered, isLoading, onAnswer, timerDurationSeconds]);

  const handleSelectAnswer = (index: number) => {
    if (isAnswered || isLoading) return;

    setSelectedIndex(index);
    setIsAnswered(true);

    const isCorrect = index === question.correct_answer_index;
    const timeSpent = timerDurationSeconds - timeLeft;

    if (isCorrect) {
      sound.playCorrect();
    } else {
      sound.playIncorrect();
    }

    onAnswer(index, isCorrect, timeSpent);
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'Música': return <Music className="w-4 h-4 text-amber-400" />;
      case 'Cine & TV': return <Tv className="w-4 h-4 text-red-400" />;
      case 'Deportes': return <Trophy className="w-4 h-4 text-cyan-400" />;
      case 'Eventos': return <Boxes className="w-4 h-4 text-emerald-400" />;
      default: return <Sparkles className="w-4 h-4 text-amber-400" />;
    }
  };

  const getDecadeBadgeStyle = (decade: string) => {
    switch (decade) {
      case '70':
      case '70s': return 'bg-amber-500/20 text-amber-300 border-amber-500/50';
      case '80':
      case '80s': return 'bg-red-500/20 text-red-300 border-red-500/50';
      case '90':
      case '90s': return 'bg-cyan-500/20 text-cyan-300 border-cyan-500/50';
      default: return 'bg-amber-500/20 text-amber-300 border-amber-500/50';
    }
  };

  const progressPercent = (timeLeft / timerDurationSeconds) * 100;

  if (isLoading) {
    return (
      <div className="w-full bg-[#181522] border-2 border-amber-500/30 rounded-2xl p-8 text-center shadow-xl animate-pulse flex flex-col items-center justify-center min-h-[320px]">
        <div className="w-12 h-12 rounded-full border-4 border-amber-400 border-t-transparent animate-spin mb-4"></div>
        <h3 className="font-righteous text-xl text-amber-300 mb-2">Generando Pregunta Retro...</h3>
        <p className="text-xs text-amber-200/60 max-w-md">
          Sintonizando la frecuencia temporal de los {question.decade || '80'} en la categoría de {question.category || 'Música'}...
        </p>
      </div>
    );
  }

  return (
    <div className="w-full bg-[#1a1724] border-2 border-amber-500/30 rounded-2xl p-4 sm:p-6 shadow-2xl relative overflow-hidden">
      {/* Timer Bar */}
      <div className="w-full bg-zinc-900 rounded-full h-2 mb-4 overflow-hidden border border-zinc-800">
        <div
          className={`h-full transition-all duration-1000 ${
            progressPercent < 30 ? 'bg-red-500' : progressPercent < 60 ? 'bg-amber-500' : 'bg-emerald-500'
          }`}
          style={{ width: `${progressPercent}%` }}
        ></div>
      </div>

      {/* Meta Headers */}
      <div className="flex flex-wrap items-center justify-between gap-2 mb-4">
        <div className="flex items-center gap-2">
          {/* Decade Tag */}
          <span className={`px-3 py-1 rounded-full text-xs font-righteous border ${getDecadeBadgeStyle(question.decade)}`}>
            {question.decade}
          </span>

          {/* Category Tag */}
          <span className="flex items-center gap-1.5 px-3 py-1 bg-zinc-900 border border-zinc-700/80 rounded-full text-xs font-bold text-zinc-200">
            {getCategoryIcon(question.category)}
            <span>{question.category}</span>
          </span>

          {/* Difficulty Tag */}
          <span className={`px-2.5 py-0.5 rounded-md text-[10px] font-extrabold uppercase tracking-wider ${
            question.difficulty === 'Experto' ? 'bg-purple-900/60 text-purple-300 border border-purple-500/40' : 'bg-teal-900/60 text-teal-300 border border-teal-500/40'
          }`}>
            Nivel {question.difficulty}
          </span>
        </div>

        {/* Time Remaining Indicator */}
        <div className="flex items-center gap-1.5 text-xs font-bold font-pixel text-amber-400 bg-amber-950/60 border border-amber-500/30 px-3 py-1 rounded-lg">
          <Clock className="w-3.5 h-3.5 text-amber-400" />
          <span>{timeLeft}s</span>
        </div>
      </div>

      {/* Question Text */}
      <div className="my-5">
        <h2 className="text-base sm:text-lg md:text-xl font-bold text-amber-50 leading-relaxed tracking-wide">
          {question.question || question.current_question}
        </h2>
      </div>

      {/* 4 Answer Option Buttons */}
      <div className="grid grid-cols-1 gap-2.5 my-4">
        {(question.options || question.answers_options || []).map((optionText, idx) => {
          let btnStyle = 'bg-zinc-900/80 border-zinc-800 text-zinc-200 hover:bg-zinc-800 hover:border-amber-500/40';
          let icon = null;

          if (isAnswered) {
            if (idx === question.correct_answer_index) {
              btnStyle = 'bg-emerald-950/90 border-emerald-500 text-emerald-200 ring-2 ring-emerald-500/50 shadow-lg shadow-emerald-500/20';
              icon = <CheckCircle2 className="w-5 h-5 text-emerald-400 shrink-0" />;
            } else if (idx === selectedIndex) {
              btnStyle = 'bg-red-950/90 border-red-500 text-red-200 ring-2 ring-red-500/50';
              icon = <XCircle className="w-5 h-5 text-red-400 shrink-0" />;
            } else {
              btnStyle = 'bg-zinc-900/40 border-zinc-800/40 text-zinc-600 opacity-50';
            }
          }

          return (
            <button
              key={idx}
              onClick={() => handleSelectAnswer(idx)}
              disabled={isAnswered}
              className={`w-full text-left p-3.5 sm:p-4 rounded-xl border font-semibold text-sm transition-all flex items-center justify-between gap-3 ${btnStyle}`}
            >
              <div className="flex items-center gap-3">
                <span className="w-6 h-6 rounded-full bg-amber-500/10 border border-amber-500/30 flex items-center justify-center text-xs font-bold text-amber-400 shrink-0">
                  {['A', 'B', 'C', 'D'][idx]}
                </span>
                <span>{optionText}</span>
              </div>
              {icon}
            </button>
          );
        })}
      </div>
    </div>
  );
};
