/**
 * Lesson Page
 * Displays individual lesson with video player, content, and progress tracking
 */

import React, { useEffect, useState, useRef, useCallback } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import {
  ArrowLeft,
  ArrowRight,
  Play,
  Pause,
  CheckCircle,
  Clock,
  BookOpen,
  FileText,
  Award,
  Zap,
  Lock,
  ChevronLeft,
  ChevronRight,
  Loader2,
  AlertCircle,
  List,
  X,
  Volume2,
  VolumeX,
  Maximize,
  SkipBack,
  SkipForward,
} from 'lucide-react';
import { useEducationStore } from '../../../stores/educationStore';
import type { LessonDetail, CourseModule } from '../../../types/education.types';

const contentTypeLabels = {
  video: 'Video',
  text: 'Artículo',
  quiz: 'Quiz',
  exercise: 'Ejercicio',
};

const contentTypeIcons = {
  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" />,
};

export default function Lesson() {
  const { courseSlug, lessonId } = useParams<{ courseSlug: string; lessonId: string }>();
  const navigate = useNavigate();

  const {
    currentCourse,
    currentLesson,
    loadingCourse,
    loadingLesson,
    error,
    fetchCourseBySlug,
    fetchLesson,
    updateLessonProgress,
    markLessonComplete,
    resetCurrentLesson,
  } = useEducationStore();

  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [showControls, setShowControls] = useState(true);
  const [completing, setCompleting] = useState(false);

  const videoRef = useRef<HTMLVideoElement>(null);
  const controlsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // Load course and lesson data
  useEffect(() => {
    if (courseSlug && !currentCourse) {
      fetchCourseBySlug(courseSlug);
    }
  }, [courseSlug, currentCourse, fetchCourseBySlug]);

  useEffect(() => {
    if (lessonId) {
      fetchLesson(lessonId);
    }
    return () => {
      resetCurrentLesson();
    };
  }, [lessonId, fetchLesson, resetCurrentLesson]);

  // Track video progress
  const handleTimeUpdate = useCallback(() => {
    if (videoRef.current) {
      const time = Math.floor(videoRef.current.currentTime);
      setCurrentTime(time);

      // Update progress every 10 seconds
      if (time > 0 && time % 10 === 0 && lessonId) {
        updateLessonProgress(lessonId, { videoWatchedSeconds: time });
      }
    }
  }, [lessonId, updateLessonProgress]);

  // Handle video loaded
  const handleLoadedMetadata = () => {
    if (videoRef.current) {
      setDuration(Math.floor(videoRef.current.duration));
    }
  };

  // Handle video ended
  const handleVideoEnded = async () => {
    setIsPlaying(false);
    if (lessonId && !currentLesson?.isCompleted) {
      await handleComplete();
    }
  };

  // Toggle play/pause
  const togglePlay = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  // Toggle mute
  const toggleMute = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  // Seek video
  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const time = parseInt(e.target.value, 10);
    if (videoRef.current) {
      videoRef.current.currentTime = time;
      setCurrentTime(time);
    }
  };

  // Skip forward/backward
  const skip = (seconds: number) => {
    if (videoRef.current) {
      videoRef.current.currentTime = Math.max(
        0,
        Math.min(duration, videoRef.current.currentTime + seconds)
      );
    }
  };

  // Fullscreen
  const toggleFullscreen = () => {
    if (videoRef.current) {
      if (document.fullscreenElement) {
        document.exitFullscreen();
      } else {
        videoRef.current.requestFullscreen();
      }
    }
  };

  // Show controls on mouse move
  const handleMouseMove = () => {
    setShowControls(true);
    if (controlsTimeoutRef.current) {
      clearTimeout(controlsTimeoutRef.current);
    }
    controlsTimeoutRef.current = setTimeout(() => {
      if (isPlaying) {
        setShowControls(false);
      }
    }, 3000);
  };

  // Mark lesson as complete
  const handleComplete = async () => {
    if (!lessonId || completing) return;
    setCompleting(true);
    try {
      await markLessonComplete(lessonId);
    } finally {
      setCompleting(false);
    }
  };

  // Format time
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // Find next and previous lessons
  const findAdjacentLessons = () => {
    if (!currentCourse || !currentLesson) return { prev: null, next: null };

    const allLessons: { id: string; title: string; moduleTitle: string }[] = [];
    currentCourse.modules.forEach((module) => {
      module.lessons.forEach((lesson) => {
        allLessons.push({
          id: lesson.id,
          title: lesson.title,
          moduleTitle: module.title,
        });
      });
    });

    const currentIndex = allLessons.findIndex((l) => l.id === currentLesson.id);
    return {
      prev: currentIndex > 0 ? allLessons[currentIndex - 1] : null,
      next: currentIndex < allLessons.length - 1 ? allLessons[currentIndex + 1] : null,
    };
  };

  const { prev, next } = findAdjacentLessons();

  // Loading state
  if (loadingCourse || loadingLesson) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-10 h-10 text-blue-500 animate-spin" />
      </div>
    );
  }

  // Error state
  if (error || !currentLesson) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen">
        <AlertCircle className="w-16 h-16 text-red-400 mb-4" />
        <h2 className="text-xl font-bold text-white mb-2">Lección no encontrada</h2>
        <p className="text-gray-400 mb-6">{error || 'La lección no existe o no tienes acceso'}</p>
        <Link
          to={`/education/courses/${courseSlug}`}
          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 al Curso
        </Link>
      </div>
    );
  }

  return (
    <div className="flex h-screen bg-gray-900">
      {/* Sidebar Toggle (Mobile) */}
      <button
        onClick={() => setSidebarOpen(!sidebarOpen)}
        className="fixed top-4 left-4 z-50 lg:hidden p-2 bg-gray-800 rounded-lg border border-gray-700"
      >
        {sidebarOpen ? <X className="w-5 h-5 text-white" /> : <List className="w-5 h-5 text-white" />}
      </button>

      {/* Sidebar - Course Outline */}
      <aside
        className={`fixed lg:static inset-y-0 left-0 z-40 w-80 bg-gray-800 border-r border-gray-700 transform transition-transform duration-300 ${
          sidebarOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'
        }`}
      >
        <div className="flex flex-col h-full">
          {/* Sidebar Header */}
          <div className="p-4 border-b border-gray-700">
            <Link
              to={`/education/courses/${courseSlug}`}
              className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors mb-3"
            >
              <ArrowLeft className="w-4 h-4" />
              <span className="text-sm">Volver al curso</span>
            </Link>
            <h2 className="font-bold text-white line-clamp-2">
              {currentCourse?.title || 'Cargando...'}
            </h2>
          </div>

          {/* Modules List */}
          <div className="flex-1 overflow-y-auto">
            {currentCourse?.modules.map((module) => (
              <ModuleSidebar
                key={module.id}
                module={module}
                currentLessonId={currentLesson.id}
                courseSlug={courseSlug || ''}
                onLessonClick={() => setSidebarOpen(false)}
              />
            ))}
          </div>

          {/* Progress */}
          {currentCourse?.userEnrollment && (
            <div className="p-4 border-t border-gray-700">
              <div className="flex items-center justify-between text-sm mb-2">
                <span className="text-gray-400">Progreso del curso</span>
                <span className="text-white font-medium">
                  {currentCourse.userEnrollment.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"
                  style={{ width: `${currentCourse.userEnrollment.progressPercentage}%` }}
                />
              </div>
            </div>
          )}
        </div>
      </aside>

      {/* Main Content */}
      <main className="flex-1 flex flex-col overflow-hidden">
        {/* Video Player / Content */}
        <div className="flex-1 bg-black relative" onMouseMove={handleMouseMove}>
          {currentLesson.contentType === 'video' && currentLesson.videoUrl ? (
            <>
              <video
                ref={videoRef}
                src={currentLesson.videoUrl}
                className="w-full h-full object-contain"
                onTimeUpdate={handleTimeUpdate}
                onLoadedMetadata={handleLoadedMetadata}
                onEnded={handleVideoEnded}
                onPlay={() => setIsPlaying(true)}
                onPause={() => setIsPlaying(false)}
              />

              {/* Video Controls Overlay */}
              <div
                className={`absolute inset-0 flex flex-col justify-end transition-opacity duration-300 ${
                  showControls ? 'opacity-100' : 'opacity-0'
                }`}
              >
                {/* Center Play Button */}
                <button
                  onClick={togglePlay}
                  className="absolute inset-0 flex items-center justify-center"
                >
                  <div className="p-4 rounded-full bg-black/50 hover:bg-black/70 transition-colors">
                    {isPlaying ? (
                      <Pause className="w-12 h-12 text-white" />
                    ) : (
                      <Play className="w-12 h-12 text-white" />
                    )}
                  </div>
                </button>

                {/* Bottom Controls */}
                <div className="bg-gradient-to-t from-black/80 to-transparent p-4 pt-16">
                  {/* Progress Bar */}
                  <input
                    type="range"
                    min={0}
                    max={duration}
                    value={currentTime}
                    onChange={handleSeek}
                    className="w-full h-1 bg-gray-600 rounded-full appearance-none cursor-pointer mb-3
                      [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
                      [&::-webkit-slider-thumb]:bg-blue-500 [&::-webkit-slider-thumb]:rounded-full"
                  />

                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      <button onClick={togglePlay} className="text-white hover:text-blue-400">
                        {isPlaying ? <Pause className="w-6 h-6" /> : <Play className="w-6 h-6" />}
                      </button>
                      <button onClick={() => skip(-10)} className="text-white hover:text-blue-400">
                        <SkipBack className="w-5 h-5" />
                      </button>
                      <button onClick={() => skip(10)} className="text-white hover:text-blue-400">
                        <SkipForward className="w-5 h-5" />
                      </button>
                      <button onClick={toggleMute} className="text-white hover:text-blue-400">
                        {isMuted ? <VolumeX className="w-5 h-5" /> : <Volume2 className="w-5 h-5" />}
                      </button>
                      <span className="text-sm text-gray-300">
                        {formatTime(currentTime)} / {formatTime(duration)}
                      </span>
                    </div>

                    <button onClick={toggleFullscreen} className="text-white hover:text-blue-400">
                      <Maximize className="w-5 h-5" />
                    </button>
                  </div>
                </div>
              </div>
            </>
          ) : currentLesson.contentType === 'text' ? (
            <div className="h-full overflow-y-auto p-8 bg-gray-900">
              <div className="max-w-3xl mx-auto">
                <div className="flex items-center gap-3 mb-6">
                  <div className="p-2 bg-blue-500/20 text-blue-400 rounded-lg">
                    <FileText className="w-6 h-6" />
                  </div>
                  <div>
                    <span className="text-sm text-gray-400">Artículo</span>
                    <h1 className="text-2xl font-bold text-white">{currentLesson.title}</h1>
                  </div>
                </div>

                {currentLesson.contentHtml ? (
                  <div
                    className="prose prose-invert max-w-none"
                    dangerouslySetInnerHTML={{ __html: currentLesson.contentHtml }}
                  />
                ) : currentLesson.contentMarkdown ? (
                  <div className="prose prose-invert max-w-none text-gray-300 whitespace-pre-wrap">
                    {currentLesson.contentMarkdown}
                  </div>
                ) : (
                  <p className="text-gray-400">El contenido de esta lección no está disponible.</p>
                )}
              </div>
            </div>
          ) : currentLesson.contentType === 'quiz' ? (
            <div className="h-full flex items-center justify-center bg-gray-900">
              <div className="text-center">
                <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-purple-500/20 mb-6">
                  <Award className="w-10 h-10 text-purple-400" />
                </div>
                <h2 className="text-2xl font-bold text-white mb-2">Quiz: {currentLesson.title}</h2>
                <p className="text-gray-400 mb-6">
                  Pon a prueba tus conocimientos con este quiz
                </p>
                <Link
                  to={`/education/courses/${courseSlug}/lesson/${lessonId}/quiz`}
                  className="inline-flex items-center gap-2 px-6 py-3 bg-purple-600 hover:bg-purple-500 text-white rounded-lg font-medium transition-colors"
                >
                  <Play className="w-5 h-5" />
                  Iniciar Quiz
                </Link>
              </div>
            </div>
          ) : (
            <div className="h-full flex items-center justify-center bg-gray-900">
              <div className="text-center">
                <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-yellow-500/20 mb-6">
                  <Zap className="w-10 h-10 text-yellow-400" />
                </div>
                <h2 className="text-2xl font-bold text-white mb-2">{currentLesson.title}</h2>
                <p className="text-gray-400">Ejercicio interactivo</p>
              </div>
            </div>
          )}
        </div>

        {/* Bottom Bar - Lesson Info and Navigation */}
        <div className="bg-gray-800 border-t border-gray-700 p-4">
          <div className="flex items-center justify-between">
            {/* Lesson Info */}
            <div className="flex items-center gap-4">
              <div className={`p-2 rounded-lg ${
                currentLesson.isCompleted
                  ? 'bg-green-500/20 text-green-400'
                  : 'bg-gray-700 text-gray-400'
              }`}>
                {currentLesson.isCompleted ? (
                  <CheckCircle className="w-5 h-5" />
                ) : (
                  contentTypeIcons[currentLesson.contentType]
                )}
              </div>
              <div>
                <h3 className="font-medium text-white">{currentLesson.title}</h3>
                <div className="flex items-center gap-3 text-sm text-gray-400">
                  <span className="flex items-center gap-1">
                    {contentTypeLabels[currentLesson.contentType]}
                  </span>
                  {currentLesson.durationMinutes && (
                    <span className="flex items-center gap-1">
                      <Clock className="w-4 h-4" />
                      {currentLesson.durationMinutes} min
                    </span>
                  )}
                  {currentLesson.xpReward && (
                    <span className="flex items-center gap-1 text-purple-400">
                      <Zap className="w-4 h-4" />
                      +{currentLesson.xpReward} XP
                    </span>
                  )}
                </div>
              </div>
            </div>

            {/* Actions */}
            <div className="flex items-center gap-3">
              {/* Complete Button */}
              {!currentLesson.isCompleted && (
                <button
                  onClick={handleComplete}
                  disabled={completing}
                  className="px-4 py-2 bg-green-600 hover:bg-green-500 text-white rounded-lg font-medium transition-colors flex items-center gap-2 disabled:opacity-50"
                >
                  {completing ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <CheckCircle className="w-4 h-4" />
                  )}
                  Marcar como completada
                </button>
              )}

              {/* Navigation */}
              <div className="flex items-center gap-2">
                {prev && (
                  <Link
                    to={`/education/courses/${courseSlug}/lesson/${prev.id}`}
                    className="p-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors"
                    title={`Anterior: ${prev.title}`}
                  >
                    <ChevronLeft className="w-5 h-5" />
                  </Link>
                )}
                {next && (
                  <Link
                    to={`/education/courses/${courseSlug}/lesson/${next.id}`}
                    className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors flex items-center gap-2"
                  >
                    Siguiente
                    <ChevronRight className="w-5 h-5" />
                  </Link>
                )}
                {!next && currentLesson.isCompleted && (
                  <Link
                    to={`/education/courses/${courseSlug}`}
                    className="px-4 py-2 bg-green-600 hover:bg-green-500 text-white rounded-lg font-medium transition-colors"
                  >
                    Finalizar Curso
                  </Link>
                )}
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}

// Module Sidebar Component
interface ModuleSidebarProps {
  module: CourseModule;
  currentLessonId: string;
  courseSlug: string;
  onLessonClick: () => void;
}

function ModuleSidebar({ module, currentLessonId, courseSlug, onLessonClick }: ModuleSidebarProps) {
  const [isExpanded, setIsExpanded] = useState(
    module.lessons.some((l) => l.id === currentLessonId)
  );

  return (
    <div className="border-b border-gray-700/50">
      <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">
          {isExpanded ? (
            <ChevronRight className="w-4 h-4 text-gray-400 rotate-90" />
          ) : (
            <ChevronRight className="w-4 h-4 text-gray-400" />
          )}
          <span className="font-medium text-white text-left line-clamp-1">{module.title}</span>
        </div>
        {module.isLocked && <Lock className="w-4 h-4 text-gray-500" />}
      </button>

      {isExpanded && (
        <div className="pb-2">
          {module.lessons.map((lesson) => (
            <Link
              key={lesson.id}
              to={`/education/courses/${courseSlug}/lesson/${lesson.id}`}
              onClick={onLessonClick}
              className={`flex items-center gap-3 px-4 py-2 mx-2 rounded-lg transition-colors ${
                lesson.id === currentLessonId
                  ? 'bg-blue-600 text-white'
                  : lesson.isCompleted
                  ? 'text-green-400 hover:bg-gray-700/30'
                  : 'text-gray-400 hover:bg-gray-700/30 hover:text-white'
              }`}
            >
              <div className="flex-shrink-0">
                {lesson.isCompleted ? (
                  <CheckCircle className="w-4 h-4" />
                ) : (
                  contentTypeIcons[lesson.contentType]
                )}
              </div>
              <span className="text-sm line-clamp-1">{lesson.title}</span>
              {lesson.isFree && !lesson.isCompleted && (
                <span className="ml-auto px-1.5 py-0.5 bg-green-500/20 text-green-400 text-xs rounded">
                  Gratis
                </span>
              )}
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
