
'use client';
import { useState, useMemo } from 'react';
import PageHeader from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ArrowRight, ArrowLeft, RefreshCw, Brain, Star, Heart, Flame, Users2, HelpCircle, User } from 'lucide-react';
import { triviaQuestions, type TriviaQuestion } from '@/lib/data';
import { cn } from '@/lib/utils';

const LEVEL_CONFIG = {
  Fácil: { icon: <Star className="w-6 h-6" />, color: 'text-yellow-500', bg: 'bg-yellow-50', border: 'border-yellow-200' },
  Medio: { icon: <Heart className="w-6 h-6" />, color: 'text-pink-500', bg: 'bg-pink-50', border: 'border-pink-200' },
  Difícil: { icon: <Flame className="w-6 h-6" />, color: 'text-red-500', bg: 'bg-red-50', border: 'border-red-200' },
  Pareja: { icon: <Users2 className="w-6 h-6" />, color: 'text-blue-500', bg: 'bg-blue-50', border: 'border-blue-200' },
  VF: { icon: <HelpCircle className="w-6 h-6" />, color: 'text-purple-500', bg: 'bg-purple-50', border: 'border-purple-200' },
};

const OptionsHeader = () => (
    <div className="w-full max-w-2xl grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        {[
            { name: 'Annie', color: 'text-pink-600', bg: 'bg-pink-100' },
            { name: 'Adri', color: 'text-blue-600', bg: 'bg-blue-100' },
            { name: 'Ambos', color: 'text-purple-600', bg: 'bg-purple-100' },
            { name: 'Ninguno', color: 'text-gray-600', bg: 'bg-gray-100' }
        ].map((opt) => (
            <Card key={opt.name} className={cn("border-none shadow-md", opt.bg)}>
                <CardContent className="p-4 flex flex-col items-center justify-center">
                    <User className={cn("w-5 h-5 mb-1", opt.color)} />
                    <span className={cn("font-headline font-bold text-sm", opt.color)}>{opt.name}</span>
                </CardContent>
            </Card>
        ))}
    </div>
);

const GameScreen = ({
  question,
  onNext,
  onPrevious,
  questionNumber,
  totalQuestions,
  onFinish
}: {
  question: TriviaQuestion;
  onNext: () => void;
  onPrevious: () => void;
  questionNumber: number;
  totalQuestions: number;
  onFinish: () => void;
}) => {
  const config = LEVEL_CONFIG[question.level] || LEVEL_CONFIG.Fácil;
  
  return (
    <div className="flex flex-col items-center w-full max-w-2xl animate-in fade-in zoom-in-95 duration-500">
      <OptionsHeader />
      
      <Card className={cn("shadow-2xl border-2 bg-card/80 backdrop-blur-sm w-full overflow-hidden", config.border)}>
        <div className={cn("h-2 w-full", config.color.replace('text', 'bg'))} />
        <CardHeader className="pb-2">
            <div className="flex justify-between items-center mb-6">
                <span className={cn("px-4 py-1.5 rounded-full text-xs font-bold uppercase tracking-widest", config.bg, config.color)}>
                    Nivel: {question.level}
                </span>
                <span className="text-sm font-body text-muted-foreground font-bold">
                    {questionNumber} / {totalQuestions}
                </span>
            </div>
            <CardTitle className="font-headline text-3xl md:text-4xl text-card-foreground leading-tight text-center pt-4">
            {question.question}
            </CardTitle>
        </CardHeader>
        <CardContent className="pt-10 flex flex-col items-center">
            <p className="font-body text-foreground/60 italic text-center mb-10">
                ¡Digan la respuesta a la vez en la llamada!
            </p>
            
            <div className="flex justify-between w-full gap-4">
                <Button 
                    onClick={onPrevious} 
                    disabled={questionNumber === 1}
                    variant="outline" 
                    size="lg" 
                    className="flex-1 h-14 border-2"
                >
                    <ArrowLeft className="mr-2 h-5 w-5" /> Anterior
                </Button>
                
                {questionNumber === totalQuestions ? (
                    <Button onClick={onFinish} size="lg" className="flex-1 h-14 font-headline text-lg shadow-xl">
                        Finalizar <RefreshCw className="ml-2 h-5 w-5" />
                    </Button>
                ) : (
                    <Button onClick={onNext} size="lg" className="flex-1 h-14 font-headline text-lg shadow-xl">
                        Siguiente <ArrowRight className="ml-2 h-5 w-5" />
                    </Button>
                )}
            </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default function TriviaPage() {
  const [gameState, setGameState] = useState<'welcome' | 'playing' | 'results'>('welcome');
  const [questions, setQuestions] = useState<TriviaQuestion[]>([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);

  const startGame = (level: TriviaQuestion['level'] | 'Todos') => {
    let filtered = level === 'Todos' ? [...triviaQuestions] : triviaQuestions.filter(q => q.level === level);
    // Seleccionar 8 preguntas aleatorias
    const gameQuestions = [...filtered]
        .sort(() => 0.5 - Math.random())
        .slice(0, 8);
        
    setQuestions(gameQuestions);
    setCurrentQuestionIndex(0);
    setGameState('playing');
  };

  const handleNext = () => {
    if (currentQuestionIndex < questions.length - 1) {
      setCurrentQuestionIndex(prev => prev + 1);
    }
  };

  const handlePrevious = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(prev => prev - 1);
    }
  };

  return (
    <div className="bg-transparent min-h-screen text-foreground flex flex-col">
      <PageHeader
        title="Trivia en Pareja"
        description="Ideal para vuestras videollamadas. ¿Coincidiréis en las respuestas?"
      />

      <main className="container mx-auto px-4 py-8 md:py-10 flex-grow flex items-center justify-center">
        {gameState === 'welcome' && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 max-w-4xl w-full">
            <Card className="md:col-span-2 shadow-2xl border-0 bg-card/80 backdrop-blur-sm animate-in fade-in zoom-in-95 duration-500 text-center p-8">
                <CardHeader>
                    <div className="flex justify-center mb-4"><Brain className="w-16 h-16 text-primary" /></div>
                    <CardTitle className="font-headline text-3xl">¡Listos para Jugar!</CardTitle>
                </CardHeader>
                <CardContent>
                    <p className="font-body text-foreground/70 text-lg mb-8">
                        Elegid una categoría. Jugaremos 8 preguntas al azar para ver vuestra conexión hoy.
                    </p>
                    <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                        {(Object.keys(LEVEL_CONFIG) as Array<keyof typeof LEVEL_CONFIG>).map((level) => (
                            <Button 
                                key={level} 
                                onClick={() => startGame(level)} 
                                variant="outline" 
                                className={cn("h-20 flex flex-col gap-1 border-2 transition-all hover:scale-105", LEVEL_CONFIG[level].border)}
                            >
                                <span className={LEVEL_CONFIG[level].color}>{LEVEL_CONFIG[level].icon}</span>
                                <span className="font-headline text-xs font-bold">{level}</span>
                            </Button>
                        ))}
                        <Button onClick={() => startGame('Todos')} size="lg" className="h-20 font-headline text-lg col-span-2 md:col-span-1">
                            ¡Mezclar todo!
                        </Button>
                    </div>
                </CardContent>
            </Card>
          </div>
        )}

        {gameState === 'playing' && questions.length > 0 && (
          <GameScreen
            question={questions[currentQuestionIndex]}
            onNext={handleNext}
            onPrevious={handlePrevious}
            questionNumber={currentQuestionIndex + 1}
            totalQuestions={questions.length}
            onFinish={() => setGameState('results')}
          />
        )}

        {gameState === 'results' && (
            <Card className="shadow-2xl border-0 bg-card/80 backdrop-blur-sm animate-in fade-in zoom-in-95 duration-500 w-full max-w-2xl text-center p-12">
                <CardHeader>
                    <div className="flex justify-center mb-6">
                        <Users2 className="w-24 h-24 text-primary animate-bounce" />
                    </div>
                    <CardTitle className="font-headline text-4xl text-gradient">¡Partida Terminada!</CardTitle>
                </CardHeader>
                <CardContent>
                    <p className="font-body text-xl text-foreground/80 mb-10 italic">
                        Esperamos que os hayáis reído y conocido un poquito mejor hoy. ¡Seguid creando recuerdos!
                    </p>
                    <Button onClick={() => setGameState('welcome')} size="lg" className="w-full h-16 text-lg font-headline shadow-xl">
                        Jugar de Nuevo <RefreshCw className="ml-2" />
                    </Button>
                </CardContent>
            </Card>
        )}
      </main>
      <footer className="text-center p-8 text-muted-foreground font-body">
        <p>Porque cada pequeño detalle de nosotros es un tesoro.</p>
      </footer>
    </div>
  );
}
