/**
 * AssessmentSummaryCard Component
 * Comprehensive quiz/assessment results and analysis
 * OQI-002: Modulo Educativo
 */

import React, { useState, useMemo } from 'react';
import {
  Trophy,
  Award,
  Target,
  Clock,
  CheckCircle,
  XCircle,
  TrendingUp,
  TrendingDown,
  BarChart3,
  Download,
  RefreshCw,
  ChevronDown,
  ChevronUp,
  Lightbulb,
  BookOpen,
  AlertCircle,
  Star,
  Zap,
} from 'lucide-react';

export interface QuestionResult {
  id: string;
  questionText: string;
  category: string;
  userAnswer: string;
  correctAnswer: string;
  isCorrect: boolean;
  explanation?: string;
  timeSpentSeconds: number;
}

export interface AssessmentResult {
  assessmentId: string;
  title: string;
  score: number;
  passingScore: number;
  passed: boolean;
  totalQuestions: number;
  correctAnswers: number;
  incorrectAnswers: number;
  skippedAnswers: number;
  timeSpentMinutes: number;
  timeLimitMinutes?: number;
  attemptNumber: number;
  maxAttempts?: number;
  completedAt: string;
  xpEarned: number;
  questions: QuestionResult[];
  categoryScores?: Record<string, { correct: number; total: number }>;
  previousAttempts?: { score: number; date: string }[];
}

interface AssessmentSummaryCardProps {
  result: AssessmentResult;
  classAverage?: number;
  onRetake?: () => void;
  onDownloadReport?: () => void;
  onViewCertificate?: () => void;
  onReviewQuestion?: (questionId: string) => void;
  compact?: boolean;
}

const AssessmentSummaryCard: React.FC<AssessmentSummaryCardProps> = ({
  result,
  classAverage,
  onRetake,
  onDownloadReport,
  onViewCertificate,
  onReviewQuestion,
  compact = false,
}) => {
  const [showQuestions, setShowQuestions] = useState(false);
  const [expandedQuestionId, setExpandedQuestionId] = useState<string | null>(null);
  const [filterType, setFilterType] = useState<'all' | 'correct' | 'incorrect'>('all');

  // Calculate metrics
  const metrics = useMemo(() => {
    const avgTimePerQuestion = result.timeSpentMinutes * 60 / result.totalQuestions;
    const accuracy = (result.correctAnswers / result.totalQuestions) * 100;

    // Find weakest category
    let weakestCategory = '';
    let lowestScore = 100;
    if (result.categoryScores) {
      Object.entries(result.categoryScores).forEach(([cat, scores]) => {
        const catScore = (scores.correct / scores.total) * 100;
        if (catScore < lowestScore) {
          lowestScore = catScore;
          weakestCategory = cat;
        }
      });
    }

    // Calculate score trend
    let scoreTrend = 0;
    if (result.previousAttempts && result.previousAttempts.length > 0) {
      const lastAttempt = result.previousAttempts[result.previousAttempts.length - 1];
      scoreTrend = result.score - lastAttempt.score;
    }

    return {
      accuracy,
      avgTimePerQuestion,
      weakestCategory,
      weakestCategoryScore: lowestScore,
      scoreTrend,
    };
  }, [result]);

  const filteredQuestions = useMemo(() => {
    return result.questions.filter(q => {
      if (filterType === 'correct') return q.isCorrect;
      if (filterType === 'incorrect') return !q.isCorrect;
      return true;
    });
  }, [result.questions, filterType]);

  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 = (score: number, passing: number) => {
    if (score >= passing) return 'text-green-400';
    if (score >= passing * 0.8) return 'text-yellow-400';
    return 'text-red-400';
  };

  const getScoreBg = (score: number, passing: number) => {
    if (score >= passing) return 'from-green-500/20 to-emerald-500/20 border-green-500/30';
    if (score >= passing * 0.8) return 'from-yellow-500/20 to-amber-500/20 border-yellow-500/30';
    return 'from-red-500/20 to-rose-500/20 border-red-500/30';
  };

  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 rounded-lg ${result.passed ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
            {result.passed ? (
              <Trophy className="w-5 h-5 text-green-400" />
            ) : (
              <AlertCircle className="w-5 h-5 text-red-400" />
            )}
          </div>
          <div>
            <h3 className="font-semibold text-white">{result.title}</h3>
            <p className="text-xs text-gray-500">
              Intento {result.attemptNumber}
              {result.maxAttempts && ` de ${result.maxAttempts}`}
              {' • '}
              {new Date(result.completedAt).toLocaleDateString('es-ES')}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2">
          {onDownloadReport && (
            <button
              onClick={onDownloadReport}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
              title="Descargar reporte"
            >
              <Download className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>

      {/* Score Display */}
      <div className={`p-6 rounded-xl bg-gradient-to-r ${getScoreBg(result.score, result.passingScore)} border mb-6`}>
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-baseline gap-2">
              <span className={`text-5xl font-bold ${getScoreColor(result.score, result.passingScore)}`}>
                {result.score}%
              </span>
              {metrics.scoreTrend !== 0 && (
                <span className={`flex items-center text-sm ${metrics.scoreTrend > 0 ? 'text-green-400' : 'text-red-400'}`}>
                  {metrics.scoreTrend > 0 ? <TrendingUp className="w-4 h-4" /> : <TrendingDown className="w-4 h-4" />}
                  {metrics.scoreTrend > 0 ? '+' : ''}{metrics.scoreTrend}%
                </span>
              )}
            </div>
            <p className="text-gray-400 mt-1">
              {result.passed ? 'Aprobado' : 'No aprobado'} • Minimo: {result.passingScore}%
            </p>
          </div>

          <div className="text-right">
            {result.passed && (
              <div className="flex items-center gap-2 mb-2">
                <Award className="w-6 h-6 text-yellow-400" />
                <span className="text-yellow-400 font-medium">+{result.xpEarned} XP</span>
              </div>
            )}
            {classAverage && (
              <p className="text-xs text-gray-500">
                Promedio de la clase: <span className="text-white">{classAverage}%</span>
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-4 gap-3 mb-6">
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="flex items-center justify-center gap-1 mb-1">
            <CheckCircle className="w-4 h-4 text-green-400" />
          </div>
          <div className="text-lg font-bold text-green-400">{result.correctAnswers}</div>
          <div className="text-xs text-gray-500">Correctas</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="flex items-center justify-center gap-1 mb-1">
            <XCircle className="w-4 h-4 text-red-400" />
          </div>
          <div className="text-lg font-bold text-red-400">{result.incorrectAnswers}</div>
          <div className="text-xs text-gray-500">Incorrectas</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="flex items-center justify-center gap-1 mb-1">
            <Clock className="w-4 h-4 text-blue-400" />
          </div>
          <div className="text-lg font-bold text-white">{formatTime(result.timeSpentMinutes)}</div>
          <div className="text-xs text-gray-500">Tiempo total</div>
        </div>
        <div className="p-3 bg-gray-900/50 rounded-lg text-center">
          <div className="flex items-center justify-center gap-1 mb-1">
            <Target className="w-4 h-4 text-purple-400" />
          </div>
          <div className="text-lg font-bold text-white">{metrics.accuracy.toFixed(0)}%</div>
          <div className="text-xs text-gray-500">Precision</div>
        </div>
      </div>

      {/* Category Performance */}
      {result.categoryScores && Object.keys(result.categoryScores).length > 0 && (
        <div className="mb-6">
          <h4 className="text-sm text-gray-400 mb-3 flex items-center gap-2">
            <BarChart3 className="w-4 h-4" />
            Rendimiento por Categoria
          </h4>
          <div className="space-y-2">
            {Object.entries(result.categoryScores).map(([category, scores]) => {
              const percentage = (scores.correct / scores.total) * 100;
              return (
                <div key={category}>
                  <div className="flex items-center justify-between text-xs mb-1">
                    <span className="text-gray-300">{category}</span>
                    <span className={getScoreColor(percentage, result.passingScore)}>
                      {scores.correct}/{scores.total} ({percentage.toFixed(0)}%)
                    </span>
                  </div>
                  <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
                    <div
                      className={`h-full rounded-full ${
                        percentage >= result.passingScore ? 'bg-green-500' : 'bg-red-500'
                      }`}
                      style={{ width: `${percentage}%` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Weak Areas */}
      {metrics.weakestCategory && metrics.weakestCategoryScore < result.passingScore && (
        <div className="mb-6 p-4 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
          <div className="flex items-start gap-3">
            <Lightbulb className="w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5" />
            <div>
              <p className="text-yellow-400 font-medium">Area de mejora identificada</p>
              <p className="text-sm text-gray-400 mt-1">
                Tu puntaje mas bajo fue en <span className="text-white">{metrics.weakestCategory}</span>{' '}
                ({metrics.weakestCategoryScore.toFixed(0)}%). Te recomendamos revisar este tema.
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Questions Review */}
      <div className="mb-6">
        <button
          onClick={() => setShowQuestions(!showQuestions)}
          className="w-full flex items-center justify-between p-3 bg-gray-900/50 rounded-lg hover:bg-gray-800 transition-colors"
        >
          <div className="flex items-center gap-2">
            <BookOpen className="w-4 h-4 text-gray-400" />
            <span className="text-white font-medium">Revisar Respuestas</span>
          </div>
          {showQuestions ? (
            <ChevronUp className="w-4 h-4 text-gray-500" />
          ) : (
            <ChevronDown className="w-4 h-4 text-gray-500" />
          )}
        </button>

        {showQuestions && (
          <div className="mt-3">
            {/* Filter */}
            <div className="flex items-center gap-2 mb-3">
              {(['all', 'correct', 'incorrect'] as const).map((filter) => (
                <button
                  key={filter}
                  onClick={() => setFilterType(filter)}
                  className={`px-3 py-1 rounded text-xs ${
                    filterType === filter
                      ? 'bg-blue-600 text-white'
                      : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                  }`}
                >
                  {filter === 'all' ? 'Todas' : filter === 'correct' ? 'Correctas' : 'Incorrectas'}
                </button>
              ))}
            </div>

            {/* Questions List */}
            <div className="space-y-2 max-h-[300px] overflow-y-auto">
              {filteredQuestions.map((q, index) => {
                const isExpanded = expandedQuestionId === q.id;
                return (
                  <div
                    key={q.id}
                    className={`p-3 rounded-lg border transition-all ${
                      q.isCorrect
                        ? 'bg-green-500/5 border-green-500/20'
                        : 'bg-red-500/5 border-red-500/20'
                    }`}
                  >
                    <div
                      onClick={() => setExpandedQuestionId(isExpanded ? null : q.id)}
                      className="flex items-start gap-3 cursor-pointer"
                    >
                      <div className={`p-1 rounded-full ${q.isCorrect ? 'bg-green-500/20' : 'bg-red-500/20'}`}>
                        {q.isCorrect ? (
                          <CheckCircle className="w-4 h-4 text-green-400" />
                        ) : (
                          <XCircle className="w-4 h-4 text-red-400" />
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-white text-sm">{q.questionText}</p>
                        <div className="flex items-center gap-2 mt-1">
                          <span className="text-xs text-gray-500">{q.category}</span>
                          <span className="text-xs text-gray-600">•</span>
                          <span className="text-xs text-gray-500">{q.timeSpentSeconds}s</span>
                        </div>
                      </div>
                      {isExpanded ? (
                        <ChevronUp className="w-4 h-4 text-gray-500 flex-shrink-0" />
                      ) : (
                        <ChevronDown className="w-4 h-4 text-gray-500 flex-shrink-0" />
                      )}
                    </div>

                    {isExpanded && (
                      <div className="mt-3 pt-3 border-t border-gray-700/50 text-sm">
                        <div className="mb-2">
                          <span className="text-gray-500">Tu respuesta: </span>
                          <span className={q.isCorrect ? 'text-green-400' : 'text-red-400'}>
                            {q.userAnswer}
                          </span>
                        </div>
                        {!q.isCorrect && (
                          <div className="mb-2">
                            <span className="text-gray-500">Respuesta correcta: </span>
                            <span className="text-green-400">{q.correctAnswer}</span>
                          </div>
                        )}
                        {q.explanation && (
                          <div className="mt-2 p-2 bg-gray-800/50 rounded text-gray-400 text-xs">
                            <strong>Explicacion:</strong> {q.explanation}
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* Previous Attempts Chart */}
      {result.previousAttempts && result.previousAttempts.length > 0 && (
        <div className="mb-6 p-4 bg-gray-900/50 rounded-lg">
          <h4 className="text-sm text-gray-400 mb-3 flex items-center gap-2">
            <TrendingUp className="w-4 h-4" />
            Historial de Intentos
          </h4>
          <div className="flex items-end gap-2 h-20">
            {result.previousAttempts.map((attempt, index) => {
              const height = (attempt.score / 100) * 100;
              return (
                <div
                  key={index}
                  className="flex-1 flex flex-col items-center"
                  title={`${attempt.score}% - ${new Date(attempt.date).toLocaleDateString()}`}
                >
                  <div
                    className={`w-full rounded-t ${
                      attempt.score >= result.passingScore ? 'bg-green-500' : 'bg-red-500'
                    }`}
                    style={{ height: `${height}%` }}
                  />
                  <span className="text-xs text-gray-500 mt-1">#{index + 1}</span>
                </div>
              );
            })}
            <div className="flex-1 flex flex-col items-center">
              <div
                className={`w-full rounded-t ${
                  result.score >= result.passingScore ? 'bg-blue-500' : 'bg-red-500'
                }`}
                style={{ height: `${result.score}%` }}
              />
              <span className="text-xs text-blue-400 mt-1">Actual</span>
            </div>
          </div>
        </div>
      )}

      {/* Actions */}
      <div className="flex items-center gap-3">
        {!result.passed && onRetake && (
          <button
            onClick={onRetake}
            disabled={result.maxAttempts !== undefined && result.attemptNumber >= result.maxAttempts}
            className="flex-1 flex items-center justify-center gap-2 py-2.5 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <RefreshCw className="w-4 h-4" />
            Reintentar
          </button>
        )}
        {result.passed && onViewCertificate && (
          <button
            onClick={onViewCertificate}
            className="flex-1 flex items-center justify-center gap-2 py-2.5 bg-gradient-to-r from-yellow-600 to-amber-600 hover:from-yellow-500 hover:to-amber-500 text-white rounded-lg font-medium transition-colors"
          >
            <Award className="w-4 h-4" />
            Ver Certificado
          </button>
        )}
      </div>
    </div>
  );
};

export default AssessmentSummaryCard;
