'use client';

import React, { useState, useEffect } from 'react';
import { useExam } from '@/contexts/ExamContext';
import { 
  Check, 
  X, 
  AlertCircle, 
  Lightbulb, 
  Target,
  TrendingUp,
  Award,
  Zap,
  Heart,
  Star
} from 'lucide-react';
import { cn } from '@/utils/cn';

interface AnswerFeedbackProps {
  questionIndex: number;
  selectedAnswer?: string;
  className?: string;
  showAnimation?: boolean;
  feedbackType?: 'instant' | 'delayed' | 'none';
  showEncouragement?: boolean;
}

interface FeedbackAnimation {
  type: 'success' | 'info' | 'warning' | 'celebration';
  message: string;
  icon: React.ReactNode;
  color: string;
  bgColor: string;
  borderColor: string;
}

const encouragementMessages = [
  { message: "Bagus! Terus semangat!", icon: <TrendingUp className="w-4 h-4" /> },
  { message: "Keren! Jawaban tersimpan!", icon: <Check className="w-4 h-4" /> },
  { message: "Mantap! Lanjutkan!", icon: <Target className="w-4 h-4" /> },
  { message: "Hebat! Tetap fokus!", icon: <Award className="w-4 h-4" /> },
  { message: "Luar biasa! Keep going!", icon: <Star className="w-4 h-4" /> },
  { message: "Perfect! Jawaban terekam!", icon: <Zap className="w-4 h-4" /> }
];

const milestoneMessages = [
  { milestone: 5, message: "5 soal selesai! Awal yang bagus!", icon: <Heart className="w-4 h-4" /> },
  { milestone: 10, message: "10 soal done! Separuh jalan!", icon: <Award className="w-4 h-4" /> },
  { milestone: 15, message: "15 soal clear! Almost there!", icon: <Star className="w-4 h-4" /> },
  { milestone: 20, message: "20 soal finished! Excellent!", icon: <TrendingUp className="w-4 h-4" /> }
];

export default function AnswerFeedback({
  questionIndex,
  selectedAnswer,
  className = '',
  showAnimation = true,
  feedbackType = 'instant',
  showEncouragement = true
}: AnswerFeedbackProps) {
  const { state } = useExam();
  const [feedback, setFeedback] = useState<FeedbackAnimation | null>(null);
  const [showFeedback, setShowFeedback] = useState(false);
  const [animationClass, setAnimationClass] = useState('');

  // Check if answer was just selected
  const currentAnswer = state.answers[questionIndex];
  const hasAnswer = currentAnswer !== undefined;

  useEffect(() => {
    if (hasAnswer && showAnimation && feedbackType !== 'none') {
      showAnswerFeedback();
    }
  }, [currentAnswer, hasAnswer, showAnimation, feedbackType]);

  const showAnswerFeedback = () => {
    const answeredCount = Object.keys(state.answers).length;
    const isMilestone = milestoneMessages.find(m => m.milestone === answeredCount);
    
    let feedbackData: FeedbackAnimation;

    if (isMilestone) {
      // Show milestone celebration
      feedbackData = {
        type: 'celebration',
        message: isMilestone.message,
        icon: isMilestone.icon,
        color: 'text-purple-600',
        bgColor: 'bg-purple-50',
        borderColor: 'border-purple-200'
      };
    } else if (showEncouragement) {
      // Show random encouragement
      const randomEncouragement = encouragementMessages[Math.floor(Math.random() * encouragementMessages.length)];
      feedbackData = {
        type: 'success',
        message: randomEncouragement.message,
        icon: randomEncouragement.icon,
        color: 'text-green-600',
        bgColor: 'bg-green-50',
        borderColor: 'border-green-200'
      };
    } else {
      // Show simple confirmation
      feedbackData = {
        type: 'info',
        message: 'Jawaban tersimpan',
        icon: <Check className="w-4 h-4" />,
        color: 'text-blue-600',
        bgColor: 'bg-blue-50',
        borderColor: 'border-blue-200'
      };
    }

    setFeedback(feedbackData);
    setShowFeedback(true);
    
    // Add entrance animation
    setAnimationClass('animate-slide-up');
    
    // Auto hide after delay
    const hideDelay = feedbackData.type === 'celebration' ? 3000 : 2000;
    setTimeout(() => {
      setAnimationClass('animate-slide-down');
      setTimeout(() => {
        setShowFeedback(false);
        setFeedback(null);
        setAnimationClass('');
      }, 300);
    }, hideDelay);
  };

  const getProgressFeedback = () => {
    const totalQuestions = state.examData?.questions.length || 0;
    const answeredCount = Object.keys(state.answers).length;
    const progressPercentage = (answeredCount / totalQuestions) * 100;

    if (progressPercentage >= 100) {
      return {
        message: "Semua soal telah dijawab! Siap untuk submit?",
        icon: <Award className="w-4 h-4" />,
        color: 'text-green-600',
        bgColor: 'bg-green-50',
        borderColor: 'border-green-200'
      };
    } else if (progressPercentage >= 75) {
      return {
        message: "Hampir selesai! Tinggal sedikit lagi!",
        icon: <TrendingUp className="w-4 h-4" />,
        color: 'text-blue-600',
        bgColor: 'bg-blue-50',
        borderColor: 'border-blue-200'
      };
    } else if (progressPercentage >= 50) {
      return {
        message: "Separuh jalan! Terus semangat!",
        icon: <Target className="w-4 h-4" />,
        color: 'text-orange-600',
        bgColor: 'bg-orange-50',
        borderColor: 'border-orange-200'
      };
    }

    return null;
  };

  const getTimeBasedFeedback = () => {
    const timeRemaining = state.timeRemaining;
    const totalTime = state.examData?.duration || 0;
    const timeUsedPercentage = ((totalTime - timeRemaining) / totalTime) * 100;
    const answeredCount = Object.keys(state.answers).length;
    const totalQuestions = state.examData?.questions.length || 0;
    const progressPercentage = (answeredCount / totalQuestions) * 100;

    // If time is running low but progress is good
    if (timeRemaining < 300 && progressPercentage > 80) { // Less than 5 minutes
      return {
        message: "Waktu terbatas, tapi progress bagus! Focus!",
        icon: <AlertCircle className="w-4 h-4" />,
        color: 'text-orange-600',
        bgColor: 'bg-orange-50',
        borderColor: 'border-orange-200'
      };
    }

    // If making good time
    if (timeUsedPercentage < 50 && progressPercentage > 60) {
      return {
        message: "Pace yang bagus! Waktu masih banyak!",
        icon: <Lightbulb className="w-4 h-4" />,
        color: 'text-green-600',
        bgColor: 'bg-green-50',
        borderColor: 'border-green-200'
      };
    }

    return null;
  };

  if (!showFeedback || !feedback) {
    return null;
  }

  return (
    <div className={cn('fixed top-4 right-4 z-50', className)}>
      <div 
        className={cn(
          'flex items-center space-x-3 px-4 py-3 rounded-lg border shadow-lg transition-all duration-300 min-w-[250px]',
          feedback.bgColor,
          feedback.borderColor,
          animationClass,
          // Animation classes
          showFeedback ? 'opacity-100 translate-y-0' : 'opacity-0 -translate-y-2'
        )}
      >
        {/* Icon with animation */}
        <div className={cn(
          'flex-shrink-0 transition-all duration-300',
          feedback.color,
          feedback.type === 'celebration' && 'animate-bounce'
        )}>
          {feedback.icon}
        </div>

        {/* Message */}
        <div className="flex-1">
          <div className={cn('text-sm font-medium', feedback.color)}>
            {feedback.message}
          </div>
          
          {/* Additional info for milestones */}
          {feedback.type === 'celebration' && (
            <div className="text-xs text-gray-600 mt-1">
              {Object.keys(state.answers).length} dari {state.examData?.questions.length} soal selesai
            </div>
          )}
        </div>

        {/* Close button */}
        <button
          onClick={() => {
            setAnimationClass('animate-slide-down');
            setTimeout(() => {
              setShowFeedback(false);
              setFeedback(null);
              setAnimationClass('');
            }, 300);
          }}
          className={cn(
            'flex-shrink-0 p-1 rounded-full hover:bg-black hover:bg-opacity-10 transition-colors',
            feedback.color
          )}
        >
          <X className="w-3 h-3" />
        </button>
      </div>

      {/* Celebration particles for milestones */}
      {feedback.type === 'celebration' && (
        <div className="absolute inset-0 pointer-events-none">
          {[...Array(6)].map((_, i) => (
            <div
              key={i}
              className={cn(
                'absolute w-2 h-2 rounded-full animate-ping',
                i % 2 === 0 ? 'bg-purple-400' : 'bg-pink-400'
              )}
              style={{
                left: `${20 + (i * 15)}%`,
                top: `${10 + (i % 3) * 20}%`,
                animationDelay: `${i * 0.2}s`,
                animationDuration: '1s'
              }}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// Additional component for persistent feedback panel
export function FeedbackPanel({ className = '' }: { className?: string }) {
  const { state } = useExam();
  const [currentFeedback, setCurrentFeedback] = useState<any>(null);

  useEffect(() => {
    const progressFeedback = getProgressFeedback();
    const timeFeedback = getTimeBasedFeedback();
    
    setCurrentFeedback(progressFeedback || timeFeedback);
  }, [state.answers, state.timeRemaining]);

  const getProgressFeedback = () => {
    const totalQuestions = state.examData?.questions.length || 0;
    const answeredCount = Object.keys(state.answers).length;
    const progressPercentage = (answeredCount / totalQuestions) * 100;

    if (progressPercentage >= 100) {
      return {
        message: "Semua soal telah dijawab!",
        subMessage: "Periksa kembali jawaban sebelum submit",
        icon: <Award className="w-5 h-5" />,
        color: 'text-green-600',
        bgColor: 'bg-green-50',
        borderColor: 'border-green-200'
      };
    } else if (progressPercentage >= 75) {
      return {
        message: "Progress Excellent!",
        subMessage: `${answeredCount}/${totalQuestions} soal selesai`,
        icon: <TrendingUp className="w-5 h-5" />,
        color: 'text-blue-600',
        bgColor: 'bg-blue-50',
        borderColor: 'border-blue-200'
      };
    }

    return null;
  };

  const getTimeBasedFeedback = () => {
    const timeRemaining = state.timeRemaining;
    const totalTime = state.examData?.duration || 0;
    const answeredCount = Object.keys(state.answers).length;
    const totalQuestions = state.examData?.questions.length || 0;

    if (timeRemaining < 600 && answeredCount < totalQuestions) { // Less than 10 minutes
      return {
        message: "Waktu terbatas!",
        subMessage: "Fokus pada soal yang belum dijawab",
        icon: <AlertCircle className="w-5 h-5" />,
        color: 'text-red-600',
        bgColor: 'bg-red-50',
        borderColor: 'border-red-200'
      };
    }

    return null;
  };

  if (!currentFeedback) {
    return null;
  }

  return (
    <div className={cn('p-4 rounded-lg border', currentFeedback.bgColor, currentFeedback.borderColor, className)}>
      <div className="flex items-center space-x-3">
        <div className={currentFeedback.color}>
          {currentFeedback.icon}
        </div>
        <div>
          <div className={cn('font-medium text-sm', currentFeedback.color)}>
            {currentFeedback.message}
          </div>
          <div className="text-xs text-gray-600 mt-1">
            {currentFeedback.subMessage}
          </div>
        </div>
      </div>
    </div>
  );
}