import React, { useEffect, useRef, useState } from 'react';
import './styles.sass';

const YouTubePlayer = ({ 
  videoId, 
  autoplay = false, 
  startTime = 45,
  onReady = () => {},
  className = ''
}) => {
  const iframeRef = useRef(null);
  const playerRef = useRef(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [customStartTime] = useState(startTime);
  
  console.log("YouTubePlayer rendering with videoId:", videoId, "startTime:", startTime);

  useEffect(() => {
    if (!window.YT) {
      const tag = document.createElement('script');
      tag.src = 'https://www.youtube.com/iframe_api';

      window.onYouTubeIframeAPIReady = () => {
        console.log("YouTube API ready");
      };
      
      const firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    }
  }, []);

  useEffect(() => {
    if (!videoId) return;

    const createPlayer = () => {
      if (!window.YT || !window.YT.Player) {
        console.log("YouTube API not ready, waiting...");
        setTimeout(createPlayer, 100);
        return;
      }

      if (playerRef.current) {
        playerRef.current.destroy();
        playerRef.current = null;
      }
      
      console.log("Creating YouTube player for video:", videoId);
      
      try {
        playerRef.current = new window.YT.Player(iframeRef.current, {
          height: '200',
          width: '300',
          videoId: videoId,
          playerVars: {
            'playsinline': 1,
            'controls': 1,
            'showinfo': 0,
            'rel': 0,
            'autoplay': autoplay ? 1 : 0,
            'start': startTime,
            'modestbranding': 1,
            'fs': 0,
          },
          events: {
            'onReady': (event) => {
              console.log("YouTube player ready");

              if (autoplay) {
                event.target.seekTo(startTime || 0);
                event.target.playVideo();
              }
              
              setIsLoaded(true);
              onReady();
            },
            'onError': (event) => {
              console.error("YouTube player error:", event);
            }
          }
        });
      } catch (error) {
        console.error("Error creating YouTube player:", error);
      }
    };
    
    createPlayer();

    return () => {
      if (playerRef.current) {
        try {
          playerRef.current.destroy();
          playerRef.current = null;
        } catch (e) {
          console.error("Error destroying player:", e);
        }
      }
    };
  }, [videoId, autoplay, onReady, startTime, customStartTime]);

  useEffect(() => {
    if (playerRef.current && isLoaded && customStartTime !== startTime) {
      try {
        playerRef.current.seekTo(customStartTime);
      } catch (error) {
        console.error("Error seeking to time:", error);
      }
    }
  }, [customStartTime, isLoaded]);

  return (
    <div className={`youtube-player-container visible-player ${className}`}>
      <div ref={iframeRef} className="youtube-embed" />
    </div>
  );
};

export default YouTubePlayer;
