/**
 * CourseDetail Page
 * Displays full course information with modules, lessons, and enrollment
 */

import React, { useEffect, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import {
  BookOpen,
  Clock,
  Users,
  Star,
  Play,
  Lock,
  CheckCircle,
  ChevronDown,
  ChevronRight,
  Zap,
  Award,
  ArrowLeft,
  Loader2,
  AlertCircle,
} from 'lucide-react';
import { useEducationStore } from '../../../stores/educationStore';
import type { CourseModule, LessonListItem } from '../../../types/education.types';

const difficultyColors = {
  beginner: 'bg-green-500/20 text-green-400 border-green-500/30',
  intermediate: 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30',
  advanced: 'bg-red-500/20 text-red-400 border-red-500/30',
};

const difficultyLabels = {
  beginner: 'Principiante',
  intermediate: 'Intermedio',
  advanced: 'Avanzado',
};

const contentTypeIcons = {
  video: <Play className="w-4 h-4" />,
  text: <BookOpen className="w-4 h-4" />,
  quiz: <Award className="w-4 h-4" />,
  exercise: <Zap className="w-4 h-4" />,
};

export default function CourseDetail() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const {
    currentCourse,
    loadingCourse,
    error,
    fetchCourseBySlug,
    enrollInCourse,
    resetCurrentCourse,
  } = useEducationStore();

  const [expandedModules, setExpandedModules] = useState<Set<string>>(new Set());
  const [enrolling, setEnrolling] = useState(false);

  useEffect(() => {
    if (slug) {
      fetchCourseBySlug(slug);
    }
    return () => {
      resetCurrentCourse();
    };
  }, [slug, fetchCourseBySlug, resetCurrentCourse]);

  const toggleModule = (moduleId: string) => {
    setExpandedModules((prev) => {
      const next = new Set(prev);
      if (next.has(moduleId)) {
        next.delete(moduleId);
      } else {
        next.add(moduleId);
      }
      return next;
    });
  };

  const handleEnroll = async () => {
    if (!currentCourse) return;
    setEnrolling(true);
    try {
      await enrollInCourse(currentCourse.id);
    } catch (err) {
      console.error('Error enrolling:', err);
    } finally {
      setEnrolling(false);
    }
  };

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

  if (loadingCourse) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
      </div>
    );
  }

  if (error || !currentCourse) {
    return (
      <div className="text-center py-20">
        <AlertCircle className="w-16 h-16 text-red-400 mx-auto mb-4" />
        <h2 className="text-xl font-bold text-white mb-2">Curso no encontrado</h2>
        <p className="text-gray-400 mb-6">{error || 'El curso que buscas no existe'}</p>
        <Link
          to="/education/courses"
          className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors"
        >
          <ArrowLeft className="w-5 h-5" />
          Volver a Cursos
        </Link>
      </div>
    );
  }

  const isEnrolled = !!currentCourse.userEnrollment;
  const enrollment = currentCourse.userEnrollment;

  // Find the next lesson to continue from (first incomplete lesson or last accessed)
  const getResumeLessonId = (): string | null => {
    if (!currentCourse?.modules) return null;

    // Flatten all lessons with their module order
    const allLessons: LessonListItem[] = [];
    currentCourse.modules
      .sort((a, b) => a.sortOrder - b.sortOrder)
      .forEach((module) => {
        module.lessons
          .sort((a, b) => a.sortOrder - b.sortOrder)
          .forEach((lesson) => allLessons.push(lesson));
      });

    // Find first incomplete lesson
    const incompleteLesson = allLessons.find((lesson) => !lesson.isCompleted);
    if (incompleteLesson) return incompleteLesson.id;

    // If all completed, return first lesson for review
    return allLessons[0]?.id || null;
  };

  const resumeLessonId = getResumeLessonId();

  return (
    <div className="space-y-6">
      {/* Back Link */}
      <Link
        to="/education/courses"
        className="inline-flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
      >
        <ArrowLeft className="w-4 h-4" />
        Volver a Cursos
      </Link>

      {/* Hero Section */}
      <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Left: Course Info */}
          <div className="lg:col-span-2 p-6">
            {/* Badges */}
            <div className="flex flex-wrap items-center gap-3 mb-4">
              {currentCourse.category && (
                <span className="px-3 py-1 bg-blue-500/20 text-blue-400 text-sm rounded-full">
                  {currentCourse.category.name}
                </span>
              )}
              <span
                className={`px-3 py-1 text-sm rounded-full border ${
                  difficultyColors[currentCourse.difficultyLevel]
                }`}
              >
                {difficultyLabels[currentCourse.difficultyLevel]}
              </span>
              {currentCourse.isFree && (
                <span className="px-3 py-1 bg-green-500 text-white text-sm rounded-full font-medium">
                  GRATIS
                </span>
              )}
            </div>

            {/* Title */}
            <h1 className="text-3xl font-bold text-white mb-4">{currentCourse.title}</h1>

            {/* Description */}
            {currentCourse.shortDescription && (
              <p className="text-lg text-gray-300 mb-6">{currentCourse.shortDescription}</p>
            )}

            {/* Stats */}
            <div className="flex flex-wrap items-center gap-6 text-sm">
              <div className="flex items-center gap-2 text-gray-400">
                <BookOpen className="w-5 h-5" />
                <span>{currentCourse.totalLessons} lecciones</span>
              </div>
              <div className="flex items-center gap-2 text-gray-400">
                <Clock className="w-5 h-5" />
                <span>{formatDuration(currentCourse.totalDuration)}</span>
              </div>
              <div className="flex items-center gap-2 text-gray-400">
                <Users className="w-5 h-5" />
                <span>{currentCourse.totalEnrollments.toLocaleString()} estudiantes</span>
              </div>
              <div className="flex items-center gap-2">
                <Star className="w-5 h-5 text-yellow-400 fill-yellow-400" />
                <span className="text-white font-medium">
                  {currentCourse.avgRating.toFixed(1)}
                </span>
                <span className="text-gray-500">({currentCourse.totalReviews} reseñas)</span>
              </div>
            </div>

            {/* Instructor */}
            {currentCourse.instructor && (
              <div className="mt-6 flex items-center gap-4">
                {currentCourse.instructor.avatar ? (
                  <img
                    src={currentCourse.instructor.avatar}
                    alt={currentCourse.instructor.name}
                    className="w-12 h-12 rounded-full"
                  />
                ) : (
                  <div className="w-12 h-12 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                    <span className="text-lg font-medium text-white">
                      {currentCourse.instructor.name.charAt(0)}
                    </span>
                  </div>
                )}
                <div>
                  <p className="text-sm text-gray-400">Instructor</p>
                  <p className="font-medium text-white">{currentCourse.instructor.name}</p>
                  {currentCourse.instructor.title && (
                    <p className="text-sm text-gray-500">{currentCourse.instructor.title}</p>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Right: Enrollment Card */}
          <div className="bg-gray-900 p-6 flex flex-col">
            {/* Thumbnail */}
            <div className="relative aspect-video mb-6 rounded-lg overflow-hidden bg-gray-800">
              {currentCourse.thumbnailUrl ? (
                <img
                  src={currentCourse.thumbnailUrl}
                  alt={currentCourse.title}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center">
                  <BookOpen className="w-16 h-16 text-gray-600" />
                </div>
              )}
              <div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 hover:opacity-100 transition-opacity">
                <Play className="w-16 h-16 text-white" />
              </div>
            </div>

            {/* Price */}
            {!currentCourse.isFree && currentCourse.priceUsd && (
              <div className="text-3xl font-bold text-white mb-4">
                ${currentCourse.priceUsd.toFixed(2)}
              </div>
            )}

            {/* XP Reward */}
            <div className="flex items-center gap-2 text-purple-400 mb-4">
              <Zap className="w-5 h-5" />
              <span className="font-medium">+{currentCourse.xpReward} XP al completar</span>
            </div>

            {/* Enrollment Status / Button */}
            {enrollment ? (
              <div className="space-y-4">
                {/* Progress */}
                <div>
                  <div className="flex items-center justify-between text-sm mb-2">
                    <span className="text-gray-400">Tu progreso</span>
                    <span className="text-white font-medium">
                      {enrollment.progressPercentage.toFixed(0)}%
                    </span>
                  </div>
                  <div className="h-2 bg-gray-700 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-blue-500 rounded-full transition-all"
                      style={{ width: `${enrollment.progressPercentage}%` }}
                    />
                  </div>
                  <p className="text-xs text-gray-500 mt-1">
                    {enrollment.completedLessons} de {enrollment.totalLessons} lecciones
                  </p>
                </div>

                <button
                  onClick={() => navigate(`/education/courses/${slug}/lesson/${resumeLessonId || '1'}`)}
                  className="w-full py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
                >
                  <Play className="w-5 h-5" />
                  {enrollment.progressPercentage > 0 ? 'Continuar donde lo dejaste' : 'Empezar Curso'}
                </button>
              </div>
            ) : (
              <button
                onClick={handleEnroll}
                disabled={enrolling}
                className="w-full py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
              >
                {enrolling ? (
                  <>
                    <Loader2 className="w-5 h-5 animate-spin" />
                    Inscribiendo...
                  </>
                ) : (
                  <>
                    <BookOpen className="w-5 h-5" />
                    {currentCourse.isFree ? 'Inscribirse Gratis' : 'Comprar Curso'}
                  </>
                )}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Course Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Description */}
          {currentCourse.description && (
            <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
              <h2 className="text-xl font-bold text-white mb-4">Descripción</h2>
              <div className="prose prose-invert max-w-none text-gray-300">
                {currentCourse.description}
              </div>
            </div>
          )}

          {/* Learning Objectives */}
          {currentCourse.learningObjectives.length > 0 && (
            <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
              <h2 className="text-xl font-bold text-white mb-4">Lo que aprenderás</h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                {currentCourse.learningObjectives.map((objective, index) => (
                  <div key={index} className="flex items-start gap-3">
                    <CheckCircle className="w-5 h-5 text-green-400 flex-shrink-0 mt-0.5" />
                    <span className="text-gray-300">{objective}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Requirements */}
          {currentCourse.requirements.length > 0 && (
            <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
              <h2 className="text-xl font-bold text-white mb-4">Requisitos</h2>
              <ul className="space-y-2">
                {currentCourse.requirements.map((req, index) => (
                  <li key={index} className="flex items-start gap-3 text-gray-300">
                    <ChevronRight className="w-5 h-5 text-gray-500 flex-shrink-0 mt-0.5" />
                    {req}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Curriculum */}
          <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
            <h2 className="text-xl font-bold text-white mb-4">Contenido del Curso</h2>
            <p className="text-sm text-gray-400 mb-4">
              {currentCourse.modules.length} módulos • {currentCourse.totalLessons} lecciones •{' '}
              {formatDuration(currentCourse.totalDuration)} de contenido
            </p>

            <div className="space-y-3">
              {currentCourse.modules.map((module) => (
                <ModuleAccordion
                  key={module.id}
                  module={module}
                  isExpanded={expandedModules.has(module.id)}
                  onToggle={() => toggleModule(module.id)}
                  isEnrolled={isEnrolled}
                />
              ))}
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Tags */}
          {currentCourse.tags.length > 0 && (
            <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
              <h3 className="font-medium text-white mb-3">Temas</h3>
              <div className="flex flex-wrap gap-2">
                {currentCourse.tags.map((tag) => (
                  <span
                    key={tag}
                    className="px-3 py-1 bg-gray-700 text-gray-300 text-sm rounded-full"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Instructor Bio */}
          {currentCourse.instructor?.bio && (
            <div className="bg-gray-800 rounded-xl border border-gray-700 p-6">
              <h3 className="font-medium text-white mb-3">Sobre el Instructor</h3>
              <p className="text-sm text-gray-400">{currentCourse.instructor.bio}</p>
              {currentCourse.instructor.totalStudents && (
                <div className="mt-4 flex items-center gap-4 text-sm text-gray-500">
                  <span>{currentCourse.instructor.totalStudents.toLocaleString()} estudiantes</span>
                  <span>{currentCourse.instructor.totalCourses} cursos</span>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// Module Accordion Component
interface ModuleAccordionProps {
  module: CourseModule;
  isExpanded: boolean;
  onToggle: () => void;
  isEnrolled: boolean;
}

function ModuleAccordion({ module, isExpanded, onToggle, isEnrolled }: ModuleAccordionProps) {
  const formatDuration = (minutes: number) => {
    if (minutes < 60) return `${minutes}m`;
    return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
  };

  return (
    <div className="border border-gray-700 rounded-lg overflow-hidden">
      <button
        onClick={onToggle}
        className="w-full flex items-center justify-between p-4 bg-gray-900/50 hover:bg-gray-900 transition-colors"
      >
        <div className="flex items-center gap-3">
          {isExpanded ? (
            <ChevronDown className="w-5 h-5 text-gray-400" />
          ) : (
            <ChevronRight className="w-5 h-5 text-gray-400" />
          )}
          <div className="text-left">
            <h4 className="font-medium text-white">{module.title}</h4>
            <p className="text-xs text-gray-500">
              {module.totalLessons} lecciones • {formatDuration(module.totalDuration)}
            </p>
          </div>
        </div>
        {module.isLocked && <Lock className="w-4 h-4 text-gray-500" />}
      </button>

      {isExpanded && (
        <div className="divide-y divide-gray-700/50">
          {module.lessons.map((lesson) => (
            <LessonItem key={lesson.id} lesson={lesson} isEnrolled={isEnrolled} />
          ))}
        </div>
      )}
    </div>
  );
}

// Lesson Item Component
interface LessonItemProps {
  lesson: LessonListItem;
  isEnrolled: boolean;
}

function LessonItem({ lesson, isEnrolled }: LessonItemProps) {
  const canAccess = isEnrolled || lesson.isFree;

  return (
    <div
      className={`flex items-center justify-between p-4 ${
        canAccess ? 'hover:bg-gray-700/30' : 'opacity-60'
      }`}
    >
      <div className="flex items-center gap-3">
        <div
          className={`p-2 rounded-lg ${
            lesson.isCompleted
              ? 'bg-green-500/20 text-green-400'
              : 'bg-gray-700 text-gray-400'
          }`}
        >
          {lesson.isCompleted ? (
            <CheckCircle className="w-4 h-4" />
          ) : (
            contentTypeIcons[lesson.contentType]
          )}
        </div>
        <div>
          <p className={`text-sm ${canAccess ? 'text-white' : 'text-gray-400'}`}>
            {lesson.title}
          </p>
          <p className="text-xs text-gray-500">{lesson.durationMinutes} min</p>
        </div>
      </div>

      <div className="flex items-center gap-2">
        {lesson.isFree && !isEnrolled && (
          <span className="px-2 py-0.5 bg-green-500/20 text-green-400 text-xs rounded">
            Gratis
          </span>
        )}
        {!canAccess && <Lock className="w-4 h-4 text-gray-500" />}
      </div>
    </div>
  );
}
