/**
 * VideoProgressPlayer Component
 * Enhanced video player with advanced progress tracking
 * OQI-002: Modulo Educativo
 */

import React, { useState, useRef, useEffect, useCallback } from 'react';
import {
  Play,
  Pause,
  Volume2,
  VolumeX,
  Maximize,
  Minimize,
  Settings,
  SkipBack,
  SkipForward,
  Rewind,
  FastForward,
  Bookmark,
  BookmarkCheck,
  MessageSquare,
  Repeat,
  ChevronDown,
  Clock,
  Check,
} from 'lucide-react';

export interface VideoBookmark {
  id: string;
  time: number;
  label: string;
  createdAt: string;
}

export interface VideoNote {
  id: string;
  time: number;
  content: string;
  createdAt: string;
}

interface VideoProgressPlayerProps {
  src: string;
  poster?: string;
  title?: string;
  duration?: number;
  initialProgress?: number;
  bookmarks?: VideoBookmark[];
  notes?: VideoNote[];
  onProgressUpdate?: (progress: number, currentTime: number) => void;
  onComplete?: () => void;
  onBookmarkAdd?: (time: number, label: string) => void;
  onBookmarkRemove?: (bookmarkId: string) => void;
  onNoteAdd?: (time: number, content: string) => void;
  autoResumePosition?: boolean;
  compact?: boolean;
}

const PLAYBACK_SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2];

const VideoProgressPlayer: React.FC<VideoProgressPlayerProps> = ({
  src,
  poster,
  title,
  duration: initialDuration,
  initialProgress = 0,
  bookmarks = [],
  notes = [],
  onProgressUpdate,
  onComplete,
  onBookmarkAdd,
  onBookmarkRemove,
  onNoteAdd,
  autoResumePosition = true,
  compact = false,
}) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const progressRef = useRef<HTMLDivElement>(null);
  const updateIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(initialDuration || 0);
  const [volume, setVolume] = useState(1);
  const [isMuted, setIsMuted] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [playbackSpeed, setPlaybackSpeed] = useState(1);
  const [showSettings, setShowSettings] = useState(false);
  const [showBookmarks, setShowBookmarks] = useState(false);
  const [watchedPercentage, setWatchedPercentage] = useState(initialProgress);
  const [isCompleted, setIsCompleted] = useState(false);
  const [loopStart, setLoopStart] = useState<number | null>(null);
  const [loopEnd, setLoopEnd] = useState<number | null>(null);
  const [isLooping, setIsLooping] = useState(false);
  const [showControls, setShowControls] = useState(true);
  const [newBookmarkLabel, setNewBookmarkLabel] = useState('');
  const [showBookmarkInput, setShowBookmarkInput] = useState(false);

  // Format time as MM:SS or HH:MM:SS
  const formatTime = (seconds: number) => {
    const hrs = Math.floor(seconds / 3600);
    const mins = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);

    if (hrs > 0) {
      return `${hrs}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // Handle video metadata loaded
  const handleLoadedMetadata = () => {
    if (videoRef.current) {
      setDuration(videoRef.current.duration);
      if (autoResumePosition && initialProgress > 0) {
        const resumeTime = (initialProgress / 100) * videoRef.current.duration;
        videoRef.current.currentTime = resumeTime;
      }
    }
  };

  // Handle time update
  const handleTimeUpdate = useCallback(() => {
    if (!videoRef.current) return;

    const current = videoRef.current.currentTime;
    setCurrentTime(current);

    // Calculate watched percentage
    const percentage = (current / videoRef.current.duration) * 100;
    setWatchedPercentage(Math.max(watchedPercentage, percentage));

    // Check for loop
    if (isLooping && loopEnd !== null && current >= loopEnd) {
      videoRef.current.currentTime = loopStart || 0;
    }

    // Check for completion (95% watched)
    if (percentage >= 95 && !isCompleted) {
      setIsCompleted(true);
      onComplete?.();
    }
  }, [watchedPercentage, isLooping, loopStart, loopEnd, isCompleted, onComplete]);

  // Periodic progress sync
  useEffect(() => {
    updateIntervalRef.current = setInterval(() => {
      if (videoRef.current && isPlaying) {
        onProgressUpdate?.(watchedPercentage, videoRef.current.currentTime);
      }
    }, 10000); // Sync every 10 seconds

    return () => {
      if (updateIntervalRef.current) {
        clearInterval(updateIntervalRef.current);
      }
    };
  }, [isPlaying, watchedPercentage, onProgressUpdate]);

  // Play/Pause toggle
  const togglePlay = () => {
    if (!videoRef.current) return;

    if (isPlaying) {
      videoRef.current.pause();
    } else {
      videoRef.current.play();
    }
    setIsPlaying(!isPlaying);
  };

  // Seek to position
  const handleSeek = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!videoRef.current || !progressRef.current) return;

    const rect = progressRef.current.getBoundingClientRect();
    const percentage = (e.clientX - rect.left) / rect.width;
    const newTime = percentage * duration;
    videoRef.current.currentTime = newTime;
    setCurrentTime(newTime);
  };

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

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

  // Change volume
  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newVolume = parseFloat(e.target.value);
    if (videoRef.current) {
      videoRef.current.volume = newVolume;
    }
    setVolume(newVolume);
    setIsMuted(newVolume === 0);
  };

  // Change playback speed
  const handleSpeedChange = (speed: number) => {
    if (videoRef.current) {
      videoRef.current.playbackRate = speed;
    }
    setPlaybackSpeed(speed);
    setShowSettings(false);
  };

  // Toggle fullscreen
  const toggleFullscreen = () => {
    const container = videoRef.current?.parentElement?.parentElement;
    if (!container) return;

    if (!isFullscreen) {
      container.requestFullscreen?.();
    } else {
      document.exitFullscreen?.();
    }
    setIsFullscreen(!isFullscreen);
  };

  // Add bookmark
  const handleAddBookmark = () => {
    if (!newBookmarkLabel.trim()) return;
    onBookmarkAdd?.(currentTime, newBookmarkLabel);
    setNewBookmarkLabel('');
    setShowBookmarkInput(false);
  };

  // Jump to bookmark
  const jumpToBookmark = (time: number) => {
    if (videoRef.current) {
      videoRef.current.currentTime = time;
      setCurrentTime(time);
    }
    setShowBookmarks(false);
  };

  // Set loop points
  const handleSetLoopStart = () => {
    setLoopStart(currentTime);
    if (loopEnd !== null && currentTime >= loopEnd) {
      setLoopEnd(null);
    }
  };

  const handleSetLoopEnd = () => {
    if (loopStart !== null && currentTime > loopStart) {
      setLoopEnd(currentTime);
      setIsLooping(true);
    }
  };

  const clearLoop = () => {
    setLoopStart(null);
    setLoopEnd(null);
    setIsLooping(false);
  };

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.target instanceof HTMLInputElement) return;

      switch (e.key.toLowerCase()) {
        case ' ':
        case 'k':
          e.preventDefault();
          togglePlay();
          break;
        case 'arrowleft':
        case 'j':
          skip(-10);
          break;
        case 'arrowright':
        case 'l':
          skip(10);
          break;
        case 'm':
          toggleMute();
          break;
        case 'f':
          toggleFullscreen();
          break;
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [currentTime, isPlaying, isMuted]);

  return (
    <div
      className={`relative bg-black rounded-xl overflow-hidden ${compact ? '' : 'aspect-video'}`}
      onMouseEnter={() => setShowControls(true)}
      onMouseLeave={() => setShowControls(false)}
    >
      {/* Video Element */}
      <video
        ref={videoRef}
        src={src}
        poster={poster}
        className="w-full h-full object-contain"
        onLoadedMetadata={handleLoadedMetadata}
        onTimeUpdate={handleTimeUpdate}
        onPlay={() => setIsPlaying(true)}
        onPause={() => setIsPlaying(false)}
        onEnded={() => {
          setIsPlaying(false);
          if (!isLooping) {
            onComplete?.();
          }
        }}
        onClick={togglePlay}
      />

      {/* Title Overlay */}
      {title && showControls && (
        <div className="absolute top-0 left-0 right-0 p-4 bg-gradient-to-b from-black/80 to-transparent">
          <h3 className="text-white font-medium">{title}</h3>
        </div>
      )}

      {/* Controls Overlay */}
      <div
        className={`absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/90 to-transparent p-4 transition-opacity ${
          showControls ? 'opacity-100' : 'opacity-0'
        }`}
      >
        {/* Progress Bar */}
        <div
          ref={progressRef}
          onClick={handleSeek}
          className="relative h-1.5 bg-gray-600 rounded-full cursor-pointer mb-3 group"
        >
          {/* Watched Progress */}
          <div
            className="absolute h-full bg-gray-500 rounded-full"
            style={{ width: `${watchedPercentage}%` }}
          />
          {/* Current Progress */}
          <div
            className="absolute h-full bg-blue-500 rounded-full"
            style={{ width: `${(currentTime / duration) * 100}%` }}
          />
          {/* Loop Region */}
          {loopStart !== null && loopEnd !== null && (
            <div
              className="absolute h-full bg-yellow-500/30"
              style={{
                left: `${(loopStart / duration) * 100}%`,
                width: `${((loopEnd - loopStart) / duration) * 100}%`,
              }}
            />
          )}
          {/* Bookmarks */}
          {bookmarks.map((bookmark) => (
            <div
              key={bookmark.id}
              className="absolute top-1/2 -translate-y-1/2 w-2 h-2 bg-yellow-400 rounded-full cursor-pointer hover:scale-150 transition-transform"
              style={{ left: `${(bookmark.time / duration) * 100}%` }}
              title={bookmark.label}
              onClick={(e) => {
                e.stopPropagation();
                jumpToBookmark(bookmark.time);
              }}
            />
          ))}
          {/* Hover tooltip */}
          <div className="absolute -top-8 left-1/2 -translate-x-1/2 px-2 py-1 bg-gray-800 text-white text-xs rounded opacity-0 group-hover:opacity-100 pointer-events-none">
            {formatTime(currentTime)}
          </div>
        </div>

        {/* Control Buttons */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            {/* Play/Pause */}
            <button onClick={togglePlay} className="p-2 text-white hover:bg-white/20 rounded-lg">
              {isPlaying ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5" />}
            </button>

            {/* Skip Back */}
            <button onClick={() => skip(-10)} className="p-2 text-white hover:bg-white/20 rounded-lg">
              <Rewind className="w-4 h-4" />
            </button>

            {/* Skip Forward */}
            <button onClick={() => skip(10)} className="p-2 text-white hover:bg-white/20 rounded-lg">
              <FastForward className="w-4 h-4" />
            </button>

            {/* Volume */}
            <div className="flex items-center gap-1 group">
              <button onClick={toggleMute} className="p-2 text-white hover:bg-white/20 rounded-lg">
                {isMuted || volume === 0 ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
              </button>
              <input
                type="range"
                min="0"
                max="1"
                step="0.1"
                value={volume}
                onChange={handleVolumeChange}
                className="w-0 group-hover:w-20 transition-all duration-200 accent-blue-500"
              />
            </div>

            {/* Time Display */}
            <span className="text-white text-sm ml-2">
              {formatTime(currentTime)} / {formatTime(duration)}
            </span>
          </div>

          <div className="flex items-center gap-2">
            {/* Bookmark Button */}
            <div className="relative">
              <button
                onClick={() => setShowBookmarks(!showBookmarks)}
                className="p-2 text-white hover:bg-white/20 rounded-lg"
              >
                {bookmarks.length > 0 ? (
                  <BookmarkCheck className="w-4 h-4 text-yellow-400" />
                ) : (
                  <Bookmark className="w-4 h-4" />
                )}
              </button>

              {showBookmarks && (
                <div className="absolute bottom-full right-0 mb-2 w-64 bg-gray-800 rounded-lg shadow-xl border border-gray-700 p-2 z-50">
                  <div className="text-xs text-gray-400 mb-2">Bookmarks</div>
                  {bookmarks.length === 0 ? (
                    <p className="text-xs text-gray-500 py-2">No bookmarks</p>
                  ) : (
                    <div className="max-h-32 overflow-y-auto space-y-1">
                      {bookmarks.map((b) => (
                        <div
                          key={b.id}
                          onClick={() => jumpToBookmark(b.time)}
                          className="flex items-center justify-between p-2 hover:bg-gray-700 rounded cursor-pointer"
                        >
                          <span className="text-white text-sm">{b.label}</span>
                          <span className="text-xs text-gray-400">{formatTime(b.time)}</span>
                        </div>
                      ))}
                    </div>
                  )}
                  <div className="mt-2 pt-2 border-t border-gray-700">
                    {showBookmarkInput ? (
                      <div className="flex gap-1">
                        <input
                          type="text"
                          value={newBookmarkLabel}
                          onChange={(e) => setNewBookmarkLabel(e.target.value)}
                          placeholder="Bookmark name..."
                          className="flex-1 px-2 py-1 bg-gray-900 border border-gray-700 rounded text-xs text-white"
                          onKeyDown={(e) => e.key === 'Enter' && handleAddBookmark()}
                          autoFocus
                        />
                        <button
                          onClick={handleAddBookmark}
                          className="px-2 py-1 bg-blue-600 text-white rounded text-xs"
                        >
                          Add
                        </button>
                      </div>
                    ) : (
                      <button
                        onClick={() => setShowBookmarkInput(true)}
                        className="w-full text-left px-2 py-1 text-xs text-blue-400 hover:bg-gray-700 rounded"
                      >
                        + Add bookmark at {formatTime(currentTime)}
                      </button>
                    )}
                  </div>
                </div>
              )}
            </div>

            {/* Loop Button */}
            <button
              onClick={isLooping ? clearLoop : handleSetLoopStart}
              className={`p-2 rounded-lg ${
                isLooping ? 'text-yellow-400 bg-yellow-500/20' : 'text-white hover:bg-white/20'
              }`}
              title={isLooping ? 'Clear loop' : 'Set loop start'}
            >
              <Repeat className="w-4 h-4" />
            </button>

            {/* Settings */}
            <div className="relative">
              <button
                onClick={() => setShowSettings(!showSettings)}
                className="p-2 text-white hover:bg-white/20 rounded-lg"
              >
                <Settings className="w-4 h-4" />
              </button>

              {showSettings && (
                <div className="absolute bottom-full right-0 mb-2 w-40 bg-gray-800 rounded-lg shadow-xl border border-gray-700 p-2 z-50">
                  <div className="text-xs text-gray-400 mb-2">Playback Speed</div>
                  {PLAYBACK_SPEEDS.map((speed) => (
                    <button
                      key={speed}
                      onClick={() => handleSpeedChange(speed)}
                      className={`w-full text-left px-3 py-1.5 rounded text-sm flex items-center justify-between ${
                        playbackSpeed === speed
                          ? 'bg-blue-600 text-white'
                          : 'text-gray-300 hover:bg-gray-700'
                      }`}
                    >
                      {speed}x
                      {playbackSpeed === speed && <Check className="w-4 h-4" />}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Fullscreen */}
            <button onClick={toggleFullscreen} className="p-2 text-white hover:bg-white/20 rounded-lg">
              {isFullscreen ? <Minimize className="w-4 h-4" /> : <Maximize className="w-4 h-4" />}
            </button>
          </div>
        </div>

        {/* Completion Badge */}
        {isCompleted && (
          <div className="absolute top-4 right-4 flex items-center gap-2 px-3 py-1.5 bg-green-500/20 border border-green-500/30 rounded-full">
            <Check className="w-4 h-4 text-green-400" />
            <span className="text-green-400 text-sm">Completado</span>
          </div>
        )}
      </div>

      {/* Keyboard Shortcuts Hint */}
      {showControls && !compact && (
        <div className="absolute bottom-20 right-4 text-xs text-gray-500">
          Space: Play/Pause • J/L: ±10s • M: Mute • F: Fullscreen
        </div>
      )}
    </div>
  );
};

export default VideoProgressPlayer;
