import { useEffect, useRef, useState, useCallback } from 'react';
import './YouTubePlayer.css';

const VIDEO_ID = 'wLM5bzt1xks';
const TERP1_HEADSTART = 2; // seconds ahead

export default function YouTubePlayer() {
  const youtubePlayerRef = useRef(null);
  const localVideo1Ref = useRef(null);
  const localVideo2Ref = useRef(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isReady, setIsReady] = useState(false);
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [videoTitle, setVideoTitle] = useState('');
  const timeUpdateIntervalRef = useRef(null);

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

  const startTimeTracking = useCallback(() => {
    if (timeUpdateIntervalRef.current) {
      clearInterval(timeUpdateIntervalRef.current);
    }
    timeUpdateIntervalRef.current = setInterval(() => {
      if (youtubePlayerRef.current && youtubePlayerRef.current.getCurrentTime) {
        setCurrentTime(youtubePlayerRef.current.getCurrentTime());
      }
    }, 250);
  }, []);

  const stopTimeTracking = useCallback(() => {
    if (timeUpdateIntervalRef.current) {
      clearInterval(timeUpdateIntervalRef.current);
      timeUpdateIntervalRef.current = null;
    }
  }, []);

  useEffect(() => {
    // Load the YouTube IFrame API script
    const tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    const firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    // Set up the global callback for when API is ready
    window.onYouTubeIframeAPIReady = () => {
      youtubePlayerRef.current = new window.YT.Player('youtube-player', {
        videoId: VIDEO_ID,
        playerVars: {
          playsinline: 1,
          rel: 0,
        },
        events: {
          onReady: handlePlayerReady,
          onStateChange: handleStateChange,
        },
      });
    };

    // If the API is already loaded (e.g., from a previous mount)
    if (window.YT && window.YT.Player) {
      window.onYouTubeIframeAPIReady();
    }

    return () => {
      stopTimeTracking();
      if (youtubePlayerRef.current && youtubePlayerRef.current.destroy) {
        youtubePlayerRef.current.destroy();
      }
    };
  }, [stopTimeTracking]);

  const handlePlayerReady = () => {
    setIsReady(true);
    // Get the duration of the YouTube video
    if (youtubePlayerRef.current && youtubePlayerRef.current.getDuration) {
      setDuration(youtubePlayerRef.current.getDuration());
    }
    // Get the video title (with a small delay to ensure data is available)
    setTimeout(() => {
      if (youtubePlayerRef.current && youtubePlayerRef.current.getVideoData) {
        const videoData = youtubePlayerRef.current.getVideoData();
        if (videoData && videoData.title) {
          setVideoTitle(videoData.title);
        }
      }
    }, 500);
  };

  const handleVideo1LoadedMetadata = () => {
    // Set terp1.mp4 to start 2 seconds ahead
    if (localVideo1Ref.current) {
      localVideo1Ref.current.currentTime = TERP1_HEADSTART;
    }
  };

  const playAllLocalVideos = () => {
    if (localVideo1Ref.current) {
      localVideo1Ref.current.play();
    }
    if (localVideo2Ref.current) {
      localVideo2Ref.current.play();
    }
  };

  const pauseAllLocalVideos = () => {
    if (localVideo1Ref.current) {
      localVideo1Ref.current.pause();
    }
    if (localVideo2Ref.current) {
      localVideo2Ref.current.pause();
    }
  };

  const handleStateChange = (event) => {
    // YouTube Player States:
    // -1 = unstarted, 0 = ended, 1 = playing, 2 = paused, 3 = buffering, 5 = video cued

    // Try to get video title if not already set
    if (!videoTitle && youtubePlayerRef.current && youtubePlayerRef.current.getVideoData) {
      const videoData = youtubePlayerRef.current.getVideoData();
      if (videoData && videoData.title) {
        setVideoTitle(videoData.title);
      }
    }

    if (event.data === window.YT.PlayerState.PLAYING) {
      setIsPlaying(true);
      playAllLocalVideos();
      startTimeTracking();
    } else if (
      event.data === window.YT.PlayerState.PAUSED ||
      event.data === window.YT.PlayerState.ENDED
    ) {
      setIsPlaying(false);
      pauseAllLocalVideos();
      stopTimeTracking();
    }
  };

  const handleLocalVideoPlay = () => {
    setIsPlaying(true);
    // Sync YouTube video
    if (youtubePlayerRef.current && isReady) {
      youtubePlayerRef.current.playVideo();
    }
    playAllLocalVideos();
  };

  const handleLocalVideoPause = () => {
    setIsPlaying(false);
    // Sync YouTube video
    if (youtubePlayerRef.current && isReady) {
      youtubePlayerRef.current.pauseVideo();
    }
    pauseAllLocalVideos();
  };

  const handlePlay = () => {
    // Play all videos
    if (youtubePlayerRef.current && isReady) {
      youtubePlayerRef.current.playVideo();
    }
    playAllLocalVideos();
  };

  const handlePause = () => {
    // Pause all videos
    if (youtubePlayerRef.current && isReady) {
      youtubePlayerRef.current.pauseVideo();
    }
    pauseAllLocalVideos();
  };

  const handleToggle = () => {
    if (isPlaying) {
      handlePause();
    } else {
      handlePlay();
    }
  };

  const handleSeek = (event) => {
    const newTime = parseFloat(event.target.value);
    setCurrentTime(newTime);

    // Seek YouTube video
    if (youtubePlayerRef.current && youtubePlayerRef.current.seekTo) {
      youtubePlayerRef.current.seekTo(newTime, true);
    }

    // Seek local videos (terp1 with headstart offset)
    // Clamp to video duration if seeking past the end
    if (localVideo1Ref.current) {
      const video1Duration = localVideo1Ref.current.duration || Infinity;
      const video1Time = Math.min(newTime + TERP1_HEADSTART, video1Duration);
      localVideo1Ref.current.currentTime = video1Time;
    }
    if (localVideo2Ref.current) {
      const video2Duration = localVideo2Ref.current.duration || Infinity;
      const video2Time = Math.min(newTime, video2Duration);
      localVideo2Ref.current.currentTime = video2Time;
    }
  };

  return (
    <div className="player-container">
      {videoTitle && <h1 className="video-title">{videoTitle}</h1>}
      <div className="video-section">
        <h2 className="video-label">YouTube Video</h2>
        <div className="video-wrapper">
          <div id="youtube-player"></div>
        </div>
      </div>

      <div className="timeline-container">
        <span className="time-display">{formatTime(currentTime)}</span>
        <input
          type="range"
          className="timeline-slider"
          min="0"
          max={duration || 100}
          step="0.1"
          value={currentTime}
          onChange={handleSeek}
          disabled={!isReady}
        />
        <span className="time-display">{formatTime(duration)}</span>
      </div>

      <div className="local-videos-row">
        <div className="video-section local-video-section">
          <div className="video-header">
            <h2 className="video-label">terp3.mp4</h2>
            <p className="video-note">Starting with 2 second headstart</p>
          </div>
          <div className="video-wrapper">
            <video
              ref={localVideo1Ref}
              className="local-video"
              onPlay={handleLocalVideoPlay}
              onPause={handleLocalVideoPause}
              onLoadedMetadata={handleVideo1LoadedMetadata}
            >
              <source src="/media/terp3.mp4" type="video/mp4" />
              Your browser does not support the video tag.
            </video>
          </div>
        </div>

        <div className="video-section local-video-section">
          <div className="video-header">
            <h2 className="video-label">terp4.mp4</h2>
          </div>
          <div className="video-wrapper">
            <video
              ref={localVideo2Ref}
              className="local-video"
              onPlay={handleLocalVideoPlay}
              onPause={handleLocalVideoPause}
            >
              <source src="/media/terp4.mp4" type="video/mp4" />
              Your browser does not support the video tag.
            </video>
          </div>
        </div>
      </div>

      <div className="controls">
        <button
          className="control-btn toggle-btn"
          onClick={handleToggle}
          disabled={!isReady}
        >
          {isPlaying ? '⏸ Pause' : '▶ Play'}
        </button>
      </div>
      {!isReady && <p className="loading-text">Loading player...</p>}
    </div>
  );
}
