/**
 * LessonProgress Component
 * Visual lesson navigation with progress indicators
 * OQI-002: Modulo Educativo
 */

import React, { useMemo } from 'react';
import { Link } from 'react-router-dom';
import {
  CheckCircle,
  Circle,
  Play,
  FileText,
  Award,
  Zap,
  Lock,
  ChevronRight,
  Clock,
} from 'lucide-react';
import type { CourseModule, ContentType } from '../../../types/education.types';

interface LessonInfo {
  id: string;
  title: string;
  contentType: ContentType;
  durationMinutes: number;
  isCompleted?: boolean;
  isFree?: boolean;
  isLocked?: boolean;
}

interface LessonProgressProps {
  modules: CourseModule[];
  currentLessonId: string;
  courseSlug: string;
  compact?: boolean;
  onLessonClick?: (lessonId: string) => void;
}

const contentTypeIcons: Record<ContentType, React.ReactNode> = {
  video: <Play className="w-4 h-4" />,
  text: <FileText className="w-4 h-4" />,
  quiz: <Award className="w-4 h-4" />,
  exercise: <Zap className="w-4 h-4" />,
};

const LessonProgress: React.FC<LessonProgressProps> = ({
  modules,
  currentLessonId,
  courseSlug,
  compact = false,
  onLessonClick,
}) => {
  // Flatten all lessons with module info
  const allLessons = useMemo(() => {
    const lessons: (LessonInfo & { moduleTitle: string; moduleIndex: number })[] = [];
    modules.forEach((module, moduleIndex) => {
      module.lessons.forEach((lesson) => {
        lessons.push({
          id: lesson.id,
          title: lesson.title,
          contentType: lesson.contentType,
          durationMinutes: lesson.durationMinutes,
          isCompleted: lesson.isCompleted,
          isFree: lesson.isFree,
          isLocked: module.isLocked,
          moduleTitle: module.title,
          moduleIndex,
        });
      });
    });
    return lessons;
  }, [modules]);

  // Find current lesson index
  const currentIndex = useMemo(() => {
    return allLessons.findIndex((l) => l.id === currentLessonId);
  }, [allLessons, currentLessonId]);

  // Calculate progress stats
  const stats = useMemo(() => {
    const total = allLessons.length;
    const completed = allLessons.filter((l) => l.isCompleted).length;
    const percentage = total > 0 ? Math.round((completed / total) * 100) : 0;
    return { total, completed, percentage };
  }, [allLessons]);

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

  // Compact horizontal view
  if (compact) {
    return (
      <div className="bg-gray-800/50 rounded-xl border border-gray-700 p-4">
        {/* Progress Header */}
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-white">
              Leccion {currentIndex + 1} de {stats.total}
            </span>
            <span className="text-xs text-gray-500">
              ({stats.completed} completadas)
            </span>
          </div>
          <span className="text-sm font-medium text-blue-400">{stats.percentage}%</span>
        </div>

        {/* Progress Dots */}
        <div className="flex items-center gap-1 overflow-x-auto pb-2">
          {allLessons.map((lesson, index) => {
            const isCurrent = lesson.id === currentLessonId;
            const isPast = index < currentIndex;

            return (
              <Link
                key={lesson.id}
                to={lesson.isLocked ? '#' : `/education/courses/${courseSlug}/lesson/${lesson.id}`}
                onClick={(e) => {
                  if (lesson.isLocked) {
                    e.preventDefault();
                    return;
                  }
                  onLessonClick?.(lesson.id);
                }}
                title={lesson.title}
                className={`flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center transition-all ${
                  isCurrent
                    ? 'bg-blue-600 text-white ring-2 ring-blue-400 ring-offset-2 ring-offset-gray-800'
                    : lesson.isCompleted
                    ? 'bg-green-500/20 text-green-400'
                    : lesson.isLocked
                    ? 'bg-gray-800 text-gray-600 cursor-not-allowed'
                    : 'bg-gray-700 text-gray-400 hover:bg-gray-600'
                }`}
              >
                {lesson.isCompleted ? (
                  <CheckCircle className="w-4 h-4" />
                ) : lesson.isLocked ? (
                  <Lock className="w-3 h-3" />
                ) : (
                  <span className="text-xs font-medium">{index + 1}</span>
                )}
              </Link>
            );
          })}
        </div>

        {/* Current Lesson Info */}
        {currentIndex >= 0 && allLessons[currentIndex] && (
          <div className="mt-4 pt-4 border-t border-gray-700">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-blue-500/20 rounded-lg text-blue-400">
                {contentTypeIcons[allLessons[currentIndex].contentType]}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-white truncate">
                  {allLessons[currentIndex].title}
                </p>
                <p className="text-xs text-gray-500">
                  {allLessons[currentIndex].moduleTitle}
                </p>
              </div>
              {allLessons[currentIndex].durationMinutes > 0 && (
                <span className="text-xs text-gray-400 flex items-center gap-1">
                  <Clock className="w-3 h-3" />
                  {formatTime(allLessons[currentIndex].durationMinutes)}
                </span>
              )}
            </div>
          </div>
        )}
      </div>
    );
  }

  // Full vertical view with module sections
  return (
    <div className="bg-gray-800/50 rounded-xl border border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="p-4 border-b border-gray-700">
        <div className="flex items-center justify-between mb-3">
          <h3 className="font-semibold text-white">Contenido del Curso</h3>
          <span className="text-sm text-blue-400">{stats.percentage}% completado</span>
        </div>
        <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
          <div
            className="h-full bg-gradient-to-r from-blue-600 to-green-500 rounded-full transition-all"
            style={{ width: `${stats.percentage}%` }}
          />
        </div>
        <p className="text-xs text-gray-500 mt-2">
          {stats.completed} de {stats.total} lecciones completadas
        </p>
      </div>

      {/* Module List */}
      <div className="max-h-[400px] overflow-y-auto">
        {modules.map((module, moduleIndex) => (
          <ModuleSection
            key={module.id}
            module={module}
            moduleIndex={moduleIndex}
            currentLessonId={currentLessonId}
            courseSlug={courseSlug}
            onLessonClick={onLessonClick}
          />
        ))}
      </div>
    </div>
  );
};

// Module Section Component
interface ModuleSectionProps {
  module: CourseModule;
  moduleIndex: number;
  currentLessonId: string;
  courseSlug: string;
  onLessonClick?: (lessonId: string) => void;
}

const ModuleSection: React.FC<ModuleSectionProps> = ({
  module,
  moduleIndex,
  currentLessonId,
  courseSlug,
  onLessonClick,
}) => {
  const [isExpanded, setIsExpanded] = React.useState(
    module.lessons.some((l) => l.id === currentLessonId)
  );

  const completedLessons = module.lessons.filter((l) => l.isCompleted).length;
  const totalLessons = module.lessons.length;
  const moduleProgress = totalLessons > 0 ? Math.round((completedLessons / totalLessons) * 100) : 0;

  return (
    <div className="border-b border-gray-700/50 last:border-b-0">
      {/* Module Header */}
      <button
        onClick={() => setIsExpanded(!isExpanded)}
        className="w-full flex items-center justify-between p-4 hover:bg-gray-700/30 transition-colors"
      >
        <div className="flex items-center gap-3">
          <div
            className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium ${
              moduleProgress === 100
                ? 'bg-green-500/20 text-green-400'
                : 'bg-gray-700 text-gray-400'
            }`}
          >
            {moduleProgress === 100 ? (
              <CheckCircle className="w-4 h-4" />
            ) : (
              moduleIndex + 1
            )}
          </div>
          <div className="text-left">
            <p className="font-medium text-white text-sm">{module.title}</p>
            <p className="text-xs text-gray-500">
              {completedLessons}/{totalLessons} lecciones
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          {module.isLocked && <Lock className="w-4 h-4 text-gray-500" />}
          <ChevronRight
            className={`w-4 h-4 text-gray-400 transition-transform ${
              isExpanded ? 'rotate-90' : ''
            }`}
          />
        </div>
      </button>

      {/* Module Lessons */}
      {isExpanded && (
        <div className="pb-2">
          {module.lessons.map((lesson, lessonIndex) => {
            const isCurrent = lesson.id === currentLessonId;

            return (
              <Link
                key={lesson.id}
                to={module.isLocked ? '#' : `/education/courses/${courseSlug}/lesson/${lesson.id}`}
                onClick={(e) => {
                  if (module.isLocked) {
                    e.preventDefault();
                    return;
                  }
                  onLessonClick?.(lesson.id);
                }}
                className={`flex items-center gap-3 px-4 py-2.5 mx-2 rounded-lg transition-colors ${
                  isCurrent
                    ? 'bg-blue-600 text-white'
                    : lesson.isCompleted
                    ? 'text-green-400 hover:bg-gray-700/30'
                    : module.isLocked
                    ? 'text-gray-600 cursor-not-allowed'
                    : 'text-gray-400 hover:bg-gray-700/30 hover:text-white'
                }`}
              >
                {/* Status Icon */}
                <div className="flex-shrink-0">
                  {lesson.isCompleted ? (
                    <CheckCircle className="w-4 h-4" />
                  ) : module.isLocked ? (
                    <Lock className="w-4 h-4" />
                  ) : (
                    contentTypeIcons[lesson.contentType]
                  )}
                </div>

                {/* Lesson Info */}
                <div className="flex-1 min-w-0">
                  <p className="text-sm truncate">{lesson.title}</p>
                </div>

                {/* Duration */}
                {lesson.durationMinutes > 0 && (
                  <span className="text-xs opacity-60 flex-shrink-0">
                    {lesson.durationMinutes}m
                  </span>
                )}

                {/* Free Badge */}
                {lesson.isFree && !lesson.isCompleted && !isCurrent && (
                  <span className="px-1.5 py-0.5 bg-green-500/20 text-green-400 text-xs rounded flex-shrink-0">
                    Gratis
                  </span>
                )}
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default LessonProgress;
