import { useState, useEffect, useRef } from 'react';

import YouTubePlayer from 'youtube-player';

import Stack, { StackProps } from '@material-hu/mui/Stack';

import { getVideoId } from 'src/utils/video';

enum PlayerState {
  UNSTARTED = -1,
  ENDED = 0,
  PLAYING = 1,
  PAUSED = 2,
  BUFFERING = 3,
  CUED = 5,
}

export type YoutubeVideoProps = StackProps & {
  src: string;
  onEnded?: (event: any) => void;
};

export const YoutubeVideo = ({
  src,
  onEnded,
  ...stackProps
}: YoutubeVideoProps) => {
  const [player, setPlayer] = useState(null);
  const playerRef = useRef(null);

  useEffect(() => {
    if (!playerRef.current) return;

    const newPlayer = YouTubePlayer(playerRef.current, {
      videoId: getVideoId(src),
    });

    setPlayer(newPlayer);

    return () => {
      setPlayer(null);
      playerRef.current = null;
    };
  }, [playerRef]);

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

    const listener = player.on('stateChange', (event: any) => {
      if (event.data !== PlayerState.ENDED) return;
      onEnded?.(event);
    });

    return () => {
      if (!player) return;
      player.off(listener);
    };
  }, [player, onEnded]);

  return (
    <Stack
      className="YoutubeVideo-root"
      {...stackProps}
      ref={playerRef}
    />
  );
};

export default YoutubeVideo;
