/**
 * QuizHistoryCard Component
 * Displays user's quiz attempt history with scores and trends
 * OQI-002: Modulo Educativo - SUBTASK-007
 */

import React, { useState, useMemo } from 'react';
import {
  Trophy,
  Clock,
  Target,
  TrendingUp,
  TrendingDown,
  CheckCircle,
  XCircle,
  ChevronDown,
  ChevronUp,
  Calendar,
  BarChart3,
  RefreshCw,
  Award,
  Minus,
} from 'lucide-react';

export interface QuizAttemptHistory {
  id: string;
  quizId: string;
  quizTitle: string;
  score: number;
  maxScore: number;
  percentage: number;
  passed: boolean;
  passingScore: number;
  timeSpentMinutes: number;
  timeLimitMinutes?: number;
  correctAnswers: number;
  totalQuestions: number;
  xpEarned: number;
  attemptNumber: number;
  submittedAt: string;
}

interface QuizHistoryCardProps {
  attempts: QuizAttemptHistory[];
  onRetakeQuiz?: (quizId: string) => void;
  onViewDetails?: (attemptId: string) => void;
  compact?: boolean;
  limit?: number;
  showQuizTitle?: boolean;
}

const QuizHistoryCard: React.FC<QuizHistoryCardProps> = ({
  attempts,
  onRetakeQuiz,
  onViewDetails,
  compact = false,
  limit,
  showQuizTitle = true,
}) => {
  const [expanded, setExpanded] = useState(false);

  // Sort attempts by date (newest first)
  const sortedAttempts = useMemo(() => {
    return [...attempts].sort(
      (a, b) => new Date(b.submittedAt).getTime() - new Date(a.submittedAt).getTime()
    );
  }, [attempts]);

  // Calculate statistics
  const stats = useMemo(() => {
    if (attempts.length === 0) {
      return {
        totalAttempts: 0,
        passedCount: 0,
        passRate: 0,
        averageScore: 0,
        bestScore: 0,
        worstScore: 0,
        trend: 0,
        totalXpEarned: 0,
      };
    }

    const passedCount = attempts.filter((a) => a.passed).length;
    const scores = attempts.map((a) => a.percentage);
    const averageScore = scores.reduce((sum, s) => sum + s, 0) / scores.length;
    const bestScore = Math.max(...scores);
    const worstScore = Math.min(...scores);
    const totalXpEarned = attempts.reduce((sum, a) => sum + a.xpEarned, 0);

    // Calculate trend (last 3 attempts)
    let trend = 0;
    if (sortedAttempts.length >= 2) {
      const recentAttempts = sortedAttempts.slice(0, Math.min(3, sortedAttempts.length));
      const latestScore = recentAttempts[0].percentage;
      const olderScore = recentAttempts[recentAttempts.length - 1].percentage;
      trend = latestScore - olderScore;
    }

    return {
      totalAttempts: attempts.length,
      passedCount,
      passRate: (passedCount / attempts.length) * 100,
      averageScore,
      bestScore,
      worstScore,
      trend,
      totalXpEarned,
    };
  }, [attempts, sortedAttempts]);

  const displayedAttempts = limit && !expanded ? sortedAttempts.slice(0, limit) : sortedAttempts;
  const hasMore = limit ? sortedAttempts.length > limit : false;

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('es-ES', {
      day: 'numeric',
      month: 'short',
      year: 'numeric',
    });
  };

  const formatTime = (minutes: number) => {
    if (minutes < 1) return `${Math.round(minutes * 60)}s`;
    return `${Math.floor(minutes)}m ${Math.round((minutes % 1) * 60)}s`;
  };

  const getScoreColor = (percentage: number, passingScore: number) => {
    if (percentage >= passingScore) return 'text-green-400';
    if (percentage >= passingScore * 0.8) return 'text-yellow-400';
    return 'text-red-400';
  };

  const getTrendIcon = (trend: number) => {
    if (trend > 5) return <TrendingUp className="w-4 h-4 text-green-400" />;
    if (trend < -5) return <TrendingDown className="w-4 h-4 text-red-400" />;
    return <Minus className="w-4 h-4 text-gray-400" />;
  };

  if (attempts.length === 0) {
    return (
      <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
        <div className="flex items-center gap-3 mb-4">
          <div className="p-2 bg-purple-500/20 rounded-lg">
            <BarChart3 className="w-5 h-5 text-purple-400" />
          </div>
          <h3 className="font-semibold text-white">Historial de Quizzes</h3>
        </div>
        <p className="text-gray-400 text-sm text-center py-6">
          Aun no has completado ningun quiz
        </p>
      </div>
    );
  }

  return (
    <div className={`bg-gray-800/50 rounded-xl border border-gray-700 ${compact ? 'p-3' : 'p-4'}`}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-purple-500/20 rounded-lg">
            <BarChart3 className="w-5 h-5 text-purple-400" />
          </div>
          <div>
            <h3 className="font-semibold text-white">Historial de Quizzes</h3>
            <p className="text-xs text-gray-500">{stats.totalAttempts} intentos totales</p>
          </div>
        </div>
        <div className="flex items-center gap-1">
          {getTrendIcon(stats.trend)}
          <span
            className={`text-sm ${
              stats.trend > 0 ? 'text-green-400' : stats.trend < 0 ? 'text-red-400' : 'text-gray-400'
            }`}
          >
            {stats.trend > 0 ? '+' : ''}
            {stats.trend.toFixed(0)}%
          </span>
        </div>
      </div>

      {/* Statistics Summary */}
      <div className="grid grid-cols-4 gap-2 mb-4">
        <div className="p-2 bg-gray-900/50 rounded-lg text-center">
          <div className="text-lg font-bold text-white">{stats.averageScore.toFixed(0)}%</div>
          <div className="text-xs text-gray-500">Promedio</div>
        </div>
        <div className="p-2 bg-gray-900/50 rounded-lg text-center">
          <div className="text-lg font-bold text-green-400">{stats.bestScore.toFixed(0)}%</div>
          <div className="text-xs text-gray-500">Mejor</div>
        </div>
        <div className="p-2 bg-gray-900/50 rounded-lg text-center">
          <div className="text-lg font-bold text-white">{stats.passRate.toFixed(0)}%</div>
          <div className="text-xs text-gray-500">Aprobados</div>
        </div>
        <div className="p-2 bg-gray-900/50 rounded-lg text-center">
          <div className="text-lg font-bold text-purple-400">{stats.totalXpEarned}</div>
          <div className="text-xs text-gray-500">XP Total</div>
        </div>
      </div>

      {/* Attempts List */}
      <div className="space-y-2">
        {displayedAttempts.map((attempt) => (
          <div
            key={attempt.id}
            className={`p-3 rounded-lg border transition-colors ${
              attempt.passed
                ? 'bg-green-500/5 border-green-500/20 hover:border-green-500/40'
                : 'bg-red-500/5 border-red-500/20 hover:border-red-500/40'
            } ${onViewDetails ? 'cursor-pointer' : ''}`}
            onClick={() => onViewDetails?.(attempt.id)}
          >
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div
                  className={`p-1.5 rounded-full ${
                    attempt.passed ? 'bg-green-500/20' : 'bg-red-500/20'
                  }`}
                >
                  {attempt.passed ? (
                    <CheckCircle className="w-4 h-4 text-green-400" />
                  ) : (
                    <XCircle className="w-4 h-4 text-red-400" />
                  )}
                </div>
                <div>
                  {showQuizTitle && (
                    <p className="text-sm font-medium text-white truncate max-w-[200px]">
                      {attempt.quizTitle}
                    </p>
                  )}
                  <div className="flex items-center gap-2 text-xs text-gray-500">
                    <span className="flex items-center gap-1">
                      <Calendar className="w-3 h-3" />
                      {formatDate(attempt.submittedAt)}
                    </span>
                    <span className="flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      {formatTime(attempt.timeSpentMinutes)}
                    </span>
                    <span>Intento #{attempt.attemptNumber}</span>
                  </div>
                </div>
              </div>

              <div className="text-right">
                <div
                  className={`text-lg font-bold ${getScoreColor(
                    attempt.percentage,
                    attempt.passingScore
                  )}`}
                >
                  {attempt.percentage.toFixed(0)}%
                </div>
                <div className="text-xs text-gray-500">
                  {attempt.correctAnswers}/{attempt.totalQuestions}
                </div>
                {attempt.xpEarned > 0 && (
                  <div className="text-xs text-purple-400 flex items-center justify-end gap-1">
                    <Award className="w-3 h-3" />+{attempt.xpEarned} XP
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Show More / Less */}
      {hasMore && (
        <button
          onClick={() => setExpanded(!expanded)}
          className="w-full mt-3 py-2 text-sm text-gray-400 hover:text-white transition-colors flex items-center justify-center gap-1"
        >
          {expanded ? (
            <>
              <ChevronUp className="w-4 h-4" />
              Mostrar menos
            </>
          ) : (
            <>
              <ChevronDown className="w-4 h-4" />
              Ver {sortedAttempts.length - (limit || 0)} mas
            </>
          )}
        </button>
      )}

      {/* Retake Button */}
      {onRetakeQuiz && sortedAttempts.length > 0 && !sortedAttempts[0].passed && (
        <button
          onClick={() => onRetakeQuiz(sortedAttempts[0].quizId)}
          className="w-full mt-4 py-2.5 bg-purple-600 hover:bg-purple-500 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
        >
          <RefreshCw className="w-4 h-4" />
          Reintentar ultimo quiz
        </button>
      )}
    </div>
  );
};

export default QuizHistoryCard;
