'use client';

import React, { useState, useEffect, useRef } 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, ReactionTimeConfig } from '@/types';
import { CheckCircle, XCircle, Clock, Zap, Trophy } from 'lucide-react';

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

export default function TrueFalseCepatTepat({
  question,
  questionIndex,
  onAnswerChange,
  adminLanguage
}: TrueFalseCepatTepatProps) {
  const config = question.reactionTimeConfig as ReactionTimeConfig;
  const [selectedAnswer, setSelectedAnswer] = useState<boolean | null>(null);
  const [reactionTime, setReactionTime] = useState<number>(0);
  const [timeLeft, setTimeLeft] = useState<number>(config.timeLimit);
  const [isActive, setIsActive] = useState(false);
  const [showFeedback, setShowFeedback] = useState(false);
  const [score, setScore] = useState(0);
  const [isQuickAnswer, setIsQuickAnswer] = useState(false);
  const [showResults, setShowResults] = useState(false);
  
  const startTimeRef = useRef<number>(0);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    // Start the question timer
    setIsActive(true);
    startTimeRef.current = Date.now();
    
    if (config.showCountdown) {
      timerRef.current = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 100) {
            handleTimeUp();
            return 0;
          }
          return prev - 100;
        });
      }, 100);
    }

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  const handleTimeUp = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }
    setIsActive(false);
    
    if (selectedAnswer === null) {
      // Auto-submit with no answer
      handleAnswer(null, Date.now() - startTimeRef.current);
    }
  };

  const handleAnswer = (answer: boolean | null, responseTime?: number) => {
    if (!isActive || showResults) return;

    const finalReactionTime = responseTime || (Date.now() - startTimeRef.current);
    setReactionTime(finalReactionTime);
    setSelectedAnswer(answer);
    setIsActive(false);

    if (timerRef.current) {
      clearInterval(timerRef.current);
    }

    // Determine if it's a quick answer
    const isQuick = finalReactionTime <= config.quickAnswerThreshold;
    setIsQuickAnswer(isQuick);

    // Calculate score
    const correctAnswer = question.content.correctAnswers?.[0] === 1; // true = 1, false = 0
    const isCorrect = answer === correctAnswer;
    
    let calculatedScore = 0;
    if (isCorrect) {
      calculatedScore = 100; // Base score for correct answer
      if (isQuick) {
        calculatedScore += config.bonusForQuickAnswer;
      }
    } else if (answer !== null) {
      calculatedScore = Math.max(0, 100 - config.penaltyForWrongAnswer);
    }

    setScore(calculatedScore);

    const result = {
      answer: answer,
      isCorrect,
      reactionTime: finalReactionTime,
      isQuickAnswer: isQuick,
      score: calculatedScore,
      timeLeft: timeLeft,
      wasTimedOut: answer === null
    };

    onAnswerChange(result);

    if (config.instantFeedback) {
      setShowFeedback(true);
    }
  };

  const handleButtonClick = (answer: boolean) => {
    handleAnswer(answer);
  };

  const getTimePercentage = () => {
    return (timeLeft / config.timeLimit) * 100;
  };

  const getTimeColor = () => {
    const percentage = getTimePercentage();
    if (percentage > 50) return 'bg-green-500';
    if (percentage > 25) return 'bg-yellow-500';
    return 'bg-red-500';
  };

  const formatTime = (ms: number) => {
    return (ms / 1000).toFixed(1) + 's';
  };

  return (
    <Card className="w-full max-w-2xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            <Zap className="w-5 h-5 text-yellow-500" />
            True or False (Cepat-Tepat)
          </span>
          <div className="flex items-center gap-2">
            {config.trackReactionTime && reactionTime > 0 && (
              <Badge variant="outline" className="flex items-center gap-1">
                <Clock className="w-3 h-3" />
                {formatTime(reactionTime)}
              </Badge>
            )}
            {isQuickAnswer && (
              <Badge className="bg-yellow-500 text-white flex items-center gap-1">
                <Trophy className="w-3 h-3" />
                Cepat!
              </Badge>
            )}
          </div>
        </CardTitle>
        
        {/* Countdown Timer */}
        {config.showCountdown && isActive && (
          <div className="w-full bg-gray-200 rounded-full h-2 mb-2">
            <div 
              className={`h-2 rounded-full transition-all duration-100 ${getTimeColor()}`}
              style={{ width: `${getTimePercentage()}%` }}
            />
          </div>
        )}
        
        <div className="text-center">
          {config.showCountdown && (
            <p className="text-sm text-gray-500 mb-2">
              Waktu tersisa: {formatTime(timeLeft)}
            </p>
          )}
          <p className="text-lg font-medium">
            {question.content.question}
          </p>
          {question.content.description && (
            <p className="text-sm text-gray-600 mt-2">
              {question.content.description}
            </p>
          )}
        </div>
      </CardHeader>

      <CardContent className="space-y-6">
        {/* Answer Buttons */}
        <div className="grid grid-cols-2 gap-4">
          <Button
            size="lg"
            variant={selectedAnswer === true ? "default" : "outline"}
            onClick={() => handleButtonClick(true)}
            disabled={!isActive || showResults}
            className={`
              h-20 text-lg font-semibold transition-all duration-200
              ${selectedAnswer === true ? 'bg-green-600 hover:bg-green-700' : 'hover:bg-green-50 hover:border-green-300'}
              ${!isActive ? 'opacity-50' : 'hover:scale-105'}
            `}
          >
            <div className="flex flex-col items-center gap-1">
              <CheckCircle className="w-6 h-6" />
              <span>BENAR</span>
            </div>
          </Button>

          <Button
            size="lg"
            variant={selectedAnswer === false ? "default" : "outline"}
            onClick={() => handleButtonClick(false)}
            disabled={!isActive || showResults}
            className={`
              h-20 text-lg font-semibold transition-all duration-200
              ${selectedAnswer === false ? 'bg-red-600 hover:bg-red-700' : 'hover:bg-red-50 hover:border-red-300'}
              ${!isActive ? 'opacity-50' : 'hover:scale-105'}
            `}
          >
            <div className="flex flex-col items-center gap-1">
              <XCircle className="w-6 h-6" />
              <span>SALAH</span>
            </div>
          </Button>
        </div>

        {/* Instant Feedback */}
        {showFeedback && selectedAnswer !== null && (
          <div className={`
            text-center p-4 rounded-lg border-2 transition-all duration-300
            ${selectedAnswer === (question.content.correctAnswers?.[0] === 1) 
              ? 'bg-green-50 border-green-200 text-green-800' 
              : 'bg-red-50 border-red-200 text-red-800'
            }
          `}>
            <div className="flex items-center justify-center gap-2 mb-2">
              {selectedAnswer === (question.content.correctAnswers?.[0] === 1) ? (
                <CheckCircle className="w-6 h-6 text-green-600" />
              ) : (
                <XCircle className="w-6 h-6 text-red-600" />
              )}
              <span className="font-semibold text-lg">
                {selectedAnswer === (question.content.correctAnswers?.[0] === 1) ? 'Benar!' : 'Salah!'}
              </span>
            </div>
            
            <div className="space-y-1 text-sm">
              <p>Waktu reaksi: {formatTime(reactionTime)}</p>
              {isQuickAnswer && (
                <p className="text-yellow-600 font-medium">
                  🏆 Bonus jawaban cepat: +{config.bonusForQuickAnswer} poin!
                </p>
              )}
              <p>Skor: {score} poin</p>
            </div>

            {question.content.explanation && (
              <div className="mt-3 p-2 bg-white rounded border text-gray-700">
                <p className="font-medium text-sm">Penjelasan:</p>
                <p className="text-sm">{question.content.explanation}</p>
              </div>
            )}
          </div>
        )}

        {/* Instructions */}
        {isActive && (
          <div className="text-center text-sm text-gray-500 bg-blue-50 p-3 rounded">
            💡 Jawab secepat mungkin! 
            {config.quickAnswerThreshold && (
              <span> Jawaban dalam {formatTime(config.quickAnswerThreshold)} mendapat bonus poin.</span>
            )}
          </div>
        )}

        {/* Timeout Message */}
        {!isActive && selectedAnswer === null && (
          <div className="text-center p-4 bg-gray-50 rounded-lg border">
            <Clock className="w-8 h-8 text-gray-400 mx-auto mb-2" />
            <p className="text-gray-600 font-medium">Waktu habis!</p>
            <p className="text-sm text-gray-500">Tidak ada jawaban yang dipilih.</p>
          </div>
        )}

        {/* Performance Stats */}
        {reactionTime > 0 && config.trackReactionTime && (
          <div className="grid grid-cols-3 gap-4 text-center text-sm">
            <div className="p-2 bg-gray-50 rounded">
              <p className="text-gray-500">Waktu Reaksi</p>
              <p className="font-semibold">{formatTime(reactionTime)}</p>
            </div>
            <div className="p-2 bg-gray-50 rounded">
              <p className="text-gray-500">Status</p>
              <p className="font-semibold">
                {isQuickAnswer ? '⚡ Cepat' : '🐌 Normal'}
              </p>
            </div>
            <div className="p-2 bg-gray-50 rounded">
              <p className="text-gray-500">Skor</p>
              <p className="font-semibold">{score} pts</p>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}