'use client';

import React, { useState, useEffect } from 'react';
import { useExam } from '@/contexts/ExamContext';
import { 
  Star, 
  TrendingUp, 
  TrendingDown, 
  Minus,
  HelpCircle,
  CheckCircle,
  AlertTriangle,
  Info
} from 'lucide-react';
import { cn } from '@/utils/cn';

interface ConfidenceRatingProps {
  questionIndex: number;
  className?: string;
  showLabel?: boolean;
  showDescription?: boolean;
  size?: 'sm' | 'md' | 'lg';
  variant?: 'stars' | 'scale' | 'emoji';
  onRatingChange?: (rating: number) => void;
}

interface ConfidenceLevel {
  value: number;
  label: string;
  description: string;
  color: string;
  icon: React.ReactNode;
  emoji: string;
}

const confidenceLevels: ConfidenceLevel[] = [
  {
    value: 1,
    label: 'Sangat Tidak Yakin',
    description: 'Saya menebak jawaban ini',
    color: 'text-red-500',
    icon: <AlertTriangle className="w-4 h-4" />,
    emoji: '😰'
  },
  {
    value: 2,
    label: 'Tidak Yakin',
    description: 'Saya ragu dengan jawaban ini',
    color: 'text-orange-500',
    icon: <TrendingDown className="w-4 h-4" />,
    emoji: '😕'
  },
  {
    value: 3,
    label: 'Cukup Yakin',
    description: 'Saya cukup percaya dengan jawaban ini',
    color: 'text-yellow-500',
    icon: <Minus className="w-4 h-4" />,
    emoji: '😐'
  },
  {
    value: 4,
    label: 'Yakin',
    description: 'Saya yakin dengan jawaban ini',
    color: 'text-blue-500',
    icon: <TrendingUp className="w-4 h-4" />,
    emoji: '😊'
  },
  {
    value: 5,
    label: 'Sangat Yakin',
    description: 'Saya sangat yakin dengan jawaban ini',
    color: 'text-green-500',
    icon: <CheckCircle className="w-4 h-4" />,
    emoji: '😄'
  }
];

export default function ConfidenceRating({
  questionIndex,
  className = '',
  showLabel = true,
  showDescription = false,
  size = 'md',
  variant = 'stars',
  onRatingChange
}: ConfidenceRatingProps) {
  const { state } = useExam();
  const [rating, setRating] = useState<number>(0);
  const [hoveredRating, setHoveredRating] = useState<number>(0);
  const [showTooltip, setShowTooltip] = useState(false);

  // Get current answer for this question
  const currentAnswer = state.answers[questionIndex];
  const hasAnswer = currentAnswer !== undefined;

  // Load saved confidence rating (this would typically come from context or API)
  useEffect(() => {
    // In a real implementation, this would load from the exam context
    // For now, we'll use local state
    const savedRating = 0; // This should come from state.confidenceRatings[questionIndex] or similar
    setRating(savedRating);
  }, [questionIndex]);

  const handleRatingClick = (newRating: number) => {
    setRating(newRating);
    onRatingChange?.(newRating);
    
    // Here you would typically save to context or API
    // dispatch({ type: 'SET_CONFIDENCE_RATING', payload: { questionIndex, rating: newRating } });
  };

  const handleRatingHover = (hoverRating: number) => {
    setHoveredRating(hoverRating);
  };

  const handleMouseLeave = () => {
    setHoveredRating(0);
  };

  const getCurrentLevel = () => {
    const currentRating = hoveredRating || rating;
    return confidenceLevels.find(level => level.value === currentRating);
  };

  const getSizeClasses = () => {
    switch (size) {
      case 'sm':
        return {
          container: 'text-xs',
          star: 'w-4 h-4',
          button: 'w-6 h-6 text-xs',
          emoji: 'text-lg'
        };
      case 'lg':
        return {
          container: 'text-base',
          star: 'w-6 h-6',
          button: 'w-10 h-10 text-sm',
          emoji: 'text-2xl'
        };
      default:
        return {
          container: 'text-sm',
          star: 'w-5 h-5',
          button: 'w-8 h-8 text-xs',
          emoji: 'text-xl'
        };
    }
  };

  const sizeClasses = getSizeClasses();
  const currentLevel = getCurrentLevel();

  if (!hasAnswer) {
    return (
      <div className={cn('p-3 bg-gray-50 rounded-lg border border-gray-200', className)}>
        <div className="flex items-center space-x-2 text-gray-500">
          <HelpCircle className="w-4 h-4" />
          <span className="text-sm">
            Jawab soal terlebih dahulu untuk memberikan rating kepercayaan diri
          </span>
        </div>
      </div>
    );
  }

  return (
    <div className={cn('p-4 bg-white rounded-lg border border-gray-200 shadow-sm', className)}>
      {/* Header */}
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center space-x-2">
          <div className="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center">
            <TrendingUp className="w-3 h-3 text-blue-600" />
          </div>
          {showLabel && (
            <h4 className="text-sm font-medium text-gray-900">
              Tingkat Kepercayaan Diri
            </h4>
          )}
        </div>
        
        <button
          onClick={() => setShowTooltip(!showTooltip)}
          className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
        >
          <Info className="w-4 h-4" />
        </button>
      </div>

      {/* Tooltip */}
      {showTooltip && (
        <div className="mb-3 p-3 bg-blue-50 rounded-lg border border-blue-200">
          <p className="text-xs text-blue-800">
            Rating kepercayaan diri membantu Anda mengevaluasi pemahaman terhadap materi 
            dan dapat digunakan untuk review pembelajaran di masa depan.
          </p>
        </div>
      )}

      {/* Rating Display */}
      <div className="space-y-3">
        {variant === 'stars' && (
          <div className="flex items-center space-x-1">
            {[1, 2, 3, 4, 5].map((star) => {
              const isActive = star <= (hoveredRating || rating);
              const level = confidenceLevels[star - 1];
              
              return (
                <button
                  key={star}
                  onClick={() => handleRatingClick(star)}
                  onMouseEnter={() => handleRatingHover(star)}
                  onMouseLeave={handleMouseLeave}
                  className={cn(
                    'transition-all duration-200 hover:scale-110',
                    isActive ? level.color : 'text-gray-300'
                  )}
                  title={level.label}
                >
                  <Star 
                    className={cn(sizeClasses.star, isActive && 'fill-current')} 
                  />
                </button>
              );
            })}
          </div>
        )}

        {variant === 'scale' && (
          <div className="flex items-center space-x-2">
            {confidenceLevels.map((level) => {
              const isActive = level.value === (hoveredRating || rating);
              const isHovered = level.value === hoveredRating;
              
              return (
                <button
                  key={level.value}
                  onClick={() => handleRatingClick(level.value)}
                  onMouseEnter={() => handleRatingHover(level.value)}
                  onMouseLeave={handleMouseLeave}
                  className={cn(
                    sizeClasses.button,
                    'rounded-full border-2 transition-all duration-200 flex items-center justify-center font-medium',
                    isActive || isHovered
                      ? `border-current ${level.color} bg-current bg-opacity-10`
                      : 'border-gray-300 text-gray-400 hover:border-gray-400'
                  )}
                  title={level.label}
                >
                  {level.value}
                </button>
              );
            })}
          </div>
        )}

        {variant === 'emoji' && (
          <div className="flex items-center space-x-3">
            {confidenceLevels.map((level) => {
              const isActive = level.value === (hoveredRating || rating);
              const isHovered = level.value === hoveredRating;
              
              return (
                <button
                  key={level.value}
                  onClick={() => handleRatingClick(level.value)}
                  onMouseEnter={() => handleRatingHover(level.value)}
                  onMouseLeave={handleMouseLeave}
                  className={cn(
                    'transition-all duration-200 hover:scale-125 p-1 rounded-lg',
                    (isActive || isHovered) && 'bg-gray-100'
                  )}
                  title={level.label}
                >
                  <span className={sizeClasses.emoji}>
                    {level.emoji}
                  </span>
                </button>
              );
            })}
          </div>
        )}

        {/* Current Level Display */}
        {currentLevel && (
          <div className="flex items-center space-x-2 p-2 bg-gray-50 rounded-lg">
            <div className={currentLevel.color}>
              {currentLevel.icon}
            </div>
            <div>
              <div className={cn('font-medium', currentLevel.color, sizeClasses.container)}>
                {currentLevel.label}
              </div>
              {showDescription && (
                <div className="text-xs text-gray-600 mt-1">
                  {currentLevel.description}
                </div>
              )}
            </div>
          </div>
        )}

        {/* Statistics (if rating is set) */}
        {rating > 0 && (
          <div className="pt-2 border-t border-gray-100">
            <div className="flex items-center justify-between text-xs text-gray-500">
              <span>Rating Anda: {rating}/5</span>
              <span>
                {rating >= 4 ? 'Tinggi' : rating >= 3 ? 'Sedang' : 'Rendah'}
              </span>
            </div>
            
            {/* Progress Bar */}
            <div className="mt-2 w-full bg-gray-200 rounded-full h-1.5">
              <div 
                className={cn(
                  'h-1.5 rounded-full transition-all duration-300',
                  rating >= 4 ? 'bg-green-500' : rating >= 3 ? 'bg-yellow-500' : 'bg-red-500'
                )}
                style={{ width: `${(rating / 5) * 100}%` }}
              />
            </div>
          </div>
        )}
      </div>

      {/* Reset Button */}
      {rating > 0 && (
        <div className="mt-3 pt-3 border-t border-gray-100">
          <button
            onClick={() => handleRatingClick(0)}
            className="text-xs text-gray-500 hover:text-gray-700 transition-colors"
          >
            Reset Rating
          </button>
        </div>
      )}
    </div>
  );
}