/**
 * LearningPathVisualizer Component
 * Visual roadmap showing recommended learning paths
 * OQI-002: Modulo Educativo
 */

import React, { useState, useMemo } from 'react';
import {
  Map,
  BookOpen,
  CheckCircle,
  Circle,
  Lock,
  Play,
  Star,
  Clock,
  ChevronRight,
  ChevronDown,
  ChevronUp,
  Target,
  Zap,
  ArrowRight,
  Trophy,
  TrendingUp,
} from 'lucide-react';

export interface PathNode {
  id: string;
  title: string;
  type: 'course' | 'module' | 'milestone';
  status: 'locked' | 'available' | 'in_progress' | 'completed';
  progress?: number;
  xpReward: number;
  estimatedMinutes: number;
  difficulty: 'beginner' | 'intermediate' | 'advanced';
  prerequisites?: string[];
  description?: string;
  thumbnail?: string;
}

export interface LearningPath {
  id: string;
  title: string;
  description: string;
  totalXp: number;
  earnedXp: number;
  totalCourses: number;
  completedCourses: number;
  estimatedHours: number;
  nodes: PathNode[];
}

interface LearningPathVisualizerProps {
  path: LearningPath;
  currentNodeId?: string;
  onNodeClick?: (nodeId: string) => void;
  onStartNext?: () => void;
  compact?: boolean;
}

const LearningPathVisualizer: React.FC<LearningPathVisualizerProps> = ({
  path,
  currentNodeId,
  onNodeClick,
  onStartNext,
  compact = false,
}) => {
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());
  const [viewMode, setViewMode] = useState<'timeline' | 'grid'>('timeline');

  const overallProgress = useMemo(() => {
    return Math.round((path.completedCourses / path.totalCourses) * 100);
  }, [path]);

  const nextAvailableNode = useMemo(() => {
    return path.nodes.find(n => n.status === 'available');
  }, [path.nodes]);

  const currentInProgress = useMemo(() => {
    return path.nodes.find(n => n.status === 'in_progress');
  }, [path.nodes]);

  const toggleNode = (nodeId: string) => {
    const newExpanded = new Set(expandedNodes);
    if (newExpanded.has(nodeId)) {
      newExpanded.delete(nodeId);
    } else {
      newExpanded.add(nodeId);
    }
    setExpandedNodes(newExpanded);
  };

  const getStatusIcon = (status: PathNode['status'], size = 5) => {
    const sizeClass = `w-${size} h-${size}`;
    switch (status) {
      case 'completed':
        return <CheckCircle className={`${sizeClass} text-green-400`} />;
      case 'in_progress':
        return <Play className={`${sizeClass} text-blue-400`} />;
      case 'locked':
        return <Lock className={`${sizeClass} text-gray-500`} />;
      default:
        return <Circle className={`${sizeClass} text-gray-400`} />;
    }
  };

  const getDifficultyBadge = (difficulty: PathNode['difficulty']) => {
    const colors = {
      beginner: 'bg-green-500/20 text-green-400',
      intermediate: 'bg-yellow-500/20 text-yellow-400',
      advanced: 'bg-red-500/20 text-red-400',
    };
    const labels = {
      beginner: 'Principiante',
      intermediate: 'Intermedio',
      advanced: 'Avanzado',
    };
    return (
      <span className={`px-2 py-0.5 rounded text-xs ${colors[difficulty]}`}>
        {labels[difficulty]}
      </span>
    );
  };

  const formatTime = (minutes: number) => {
    if (minutes < 60) return `${minutes}m`;
    const hours = Math.floor(minutes / 60);
    return `${hours}h`;
  };

  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">
            <Map className="w-5 h-5 text-purple-400" />
          </div>
          <div>
            <h3 className="font-semibold text-white">{path.title}</h3>
            <p className="text-xs text-gray-500">{path.description}</p>
          </div>
        </div>

        {!compact && (
          <div className="flex items-center gap-2">
            <button
              onClick={() => setViewMode('timeline')}
              className={`px-3 py-1 rounded text-xs ${
                viewMode === 'timeline'
                  ? 'bg-purple-600 text-white'
                  : 'bg-gray-700 text-gray-300'
              }`}
            >
              Timeline
            </button>
            <button
              onClick={() => setViewMode('grid')}
              className={`px-3 py-1 rounded text-xs ${
                viewMode === 'grid'
                  ? 'bg-purple-600 text-white'
                  : 'bg-gray-700 text-gray-300'
              }`}
            >
              Grid
            </button>
          </div>
        )}
      </div>

      {/* Overall Progress */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center gap-4">
            <span className="text-sm text-gray-400">
              {path.completedCourses}/{path.totalCourses} cursos
            </span>
            <span className="text-sm text-gray-400 flex items-center gap-1">
              <Zap className="w-4 h-4 text-yellow-400" />
              {path.earnedXp}/{path.totalXp} XP
            </span>
          </div>
          <span className="text-lg font-bold text-white">{overallProgress}%</span>
        </div>
        <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
          <div
            className="h-full bg-gradient-to-r from-purple-600 to-pink-500 rounded-full transition-all duration-500"
            style={{ width: `${overallProgress}%` }}
          />
        </div>
      </div>

      {/* Current/Next Action */}
      {(currentInProgress || nextAvailableNode) && (
        <div className="mb-6 p-4 bg-gradient-to-r from-blue-500/10 to-purple-500/10 border border-blue-500/30 rounded-lg">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-gray-400 mb-1">
                {currentInProgress ? 'Continuar con' : 'Siguiente paso'}
              </p>
              <p className="text-white font-medium">
                {(currentInProgress || nextAvailableNode)?.title}
              </p>
              <div className="flex items-center gap-3 mt-1">
                <span className="text-xs text-gray-500 flex items-center gap-1">
                  <Clock className="w-3 h-3" />
                  {formatTime((currentInProgress || nextAvailableNode)!.estimatedMinutes)}
                </span>
                <span className="text-xs text-gray-500 flex items-center gap-1">
                  <Zap className="w-3 h-3" />
                  +{(currentInProgress || nextAvailableNode)!.xpReward} XP
                </span>
              </div>
            </div>
            <button
              onClick={() => onNodeClick?.((currentInProgress || nextAvailableNode)!.id)}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm font-medium transition-colors"
            >
              {currentInProgress ? 'Continuar' : 'Comenzar'}
              <ArrowRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {/* Path Visualization */}
      {viewMode === 'timeline' ? (
        <div className="space-y-1">
          {path.nodes.map((node, index) => {
            const isExpanded = expandedNodes.has(node.id);
            const isCurrent = node.id === currentNodeId;
            const isLast = index === path.nodes.length - 1;

            return (
              <div key={node.id} className="relative">
                {/* Connector Line */}
                {!isLast && (
                  <div
                    className={`absolute left-[19px] top-10 w-0.5 h-[calc(100%-16px)] ${
                      node.status === 'completed' ? 'bg-green-500' : 'bg-gray-700'
                    }`}
                  />
                )}

                {/* Node */}
                <div
                  onClick={() => node.status !== 'locked' && onNodeClick?.(node.id)}
                  className={`relative flex items-start gap-3 p-3 rounded-lg transition-all ${
                    node.status === 'locked'
                      ? 'opacity-50'
                      : 'cursor-pointer hover:bg-gray-800/50'
                  } ${isCurrent ? 'bg-blue-500/10 border border-blue-500/30' : ''}`}
                >
                  {/* Status Icon */}
                  <div
                    className={`relative z-10 p-2 rounded-full ${
                      node.status === 'completed'
                        ? 'bg-green-500/20'
                        : node.status === 'in_progress'
                        ? 'bg-blue-500/20'
                        : 'bg-gray-800'
                    }`}
                  >
                    {node.type === 'milestone' ? (
                      <Trophy className="w-5 h-5 text-yellow-400" />
                    ) : (
                      getStatusIcon(node.status)
                    )}
                  </div>

                  {/* Content */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <span
                          className={`font-medium ${
                            node.status === 'locked' ? 'text-gray-500' : 'text-white'
                          }`}
                        >
                          {node.title}
                        </span>
                        {getDifficultyBadge(node.difficulty)}
                      </div>
                      {node.status !== 'locked' && (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            toggleNode(node.id);
                          }}
                          className="p-1 text-gray-500 hover:text-white"
                        >
                          {isExpanded ? (
                            <ChevronUp className="w-4 h-4" />
                          ) : (
                            <ChevronDown className="w-4 h-4" />
                          )}
                        </button>
                      )}
                    </div>

                    {/* Quick Stats */}
                    <div className="flex items-center gap-3 mt-1 text-xs text-gray-500">
                      <span className="flex items-center gap-1">
                        <Clock className="w-3 h-3" />
                        {formatTime(node.estimatedMinutes)}
                      </span>
                      <span className="flex items-center gap-1">
                        <Zap className="w-3 h-3" />
                        {node.xpReward} XP
                      </span>
                      {node.progress !== undefined && node.progress > 0 && (
                        <span className="flex items-center gap-1">
                          <TrendingUp className="w-3 h-3" />
                          {node.progress}%
                        </span>
                      )}
                    </div>

                    {/* Progress Bar for In Progress */}
                    {node.status === 'in_progress' && node.progress !== undefined && (
                      <div className="mt-2">
                        <div className="h-1.5 bg-gray-700 rounded-full overflow-hidden">
                          <div
                            className="h-full bg-blue-500 rounded-full"
                            style={{ width: `${node.progress}%` }}
                          />
                        </div>
                      </div>
                    )}

                    {/* Expanded Details */}
                    {isExpanded && node.description && (
                      <div className="mt-3 pt-3 border-t border-gray-700">
                        <p className="text-sm text-gray-400">{node.description}</p>
                        {node.prerequisites && node.prerequisites.length > 0 && (
                          <div className="mt-2">
                            <span className="text-xs text-gray-500">Prerequisitos:</span>
                            <div className="flex flex-wrap gap-1 mt-1">
                              {node.prerequisites.map((prereq) => (
                                <span
                                  key={prereq}
                                  className="px-2 py-0.5 bg-gray-700 text-gray-300 rounded text-xs"
                                >
                                  {prereq}
                                </span>
                              ))}
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        /* Grid View */
        <div className="grid grid-cols-2 gap-3">
          {path.nodes.map((node) => (
            <div
              key={node.id}
              onClick={() => node.status !== 'locked' && onNodeClick?.(node.id)}
              className={`p-4 rounded-lg border transition-all ${
                node.status === 'locked'
                  ? 'bg-gray-800/30 border-gray-700 opacity-50'
                  : node.status === 'completed'
                  ? 'bg-green-500/10 border-green-500/30 cursor-pointer hover:border-green-500/50'
                  : node.status === 'in_progress'
                  ? 'bg-blue-500/10 border-blue-500/30 cursor-pointer hover:border-blue-500/50'
                  : 'bg-gray-800/50 border-gray-700 cursor-pointer hover:border-gray-600'
              }`}
            >
              <div className="flex items-start justify-between mb-2">
                {node.type === 'milestone' ? (
                  <Trophy className="w-6 h-6 text-yellow-400" />
                ) : (
                  getStatusIcon(node.status, 6)
                )}
                {getDifficultyBadge(node.difficulty)}
              </div>
              <h4 className={`font-medium mb-1 ${node.status === 'locked' ? 'text-gray-500' : 'text-white'}`}>
                {node.title}
              </h4>
              <div className="flex items-center gap-2 text-xs text-gray-500">
                <span>{formatTime(node.estimatedMinutes)}</span>
                <span>•</span>
                <span>{node.xpReward} XP</span>
              </div>
              {node.status === 'in_progress' && node.progress !== undefined && (
                <div className="mt-2">
                  <div className="h-1 bg-gray-700 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-blue-500 rounded-full"
                      style={{ width: `${node.progress}%` }}
                    />
                  </div>
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Completion Badge */}
      {overallProgress === 100 && (
        <div className="mt-6 p-4 bg-gradient-to-r from-yellow-500/10 to-amber-500/10 border border-yellow-500/30 rounded-lg text-center">
          <Trophy className="w-10 h-10 text-yellow-400 mx-auto mb-2" />
          <p className="text-yellow-400 font-bold">Path Completado!</p>
          <p className="text-xs text-gray-400 mt-1">Has dominado {path.title}</p>
        </div>
      )}
    </div>
  );
};

export default LearningPathVisualizer;
