import React, { useState } from 'react';
import YouTube, { YouTubeEvent } from 'react-youtube';

import PlayButtonIcon from '@/svgs/PlayButtonIcon/PlayButtonIcon';

import styles from './YouTubePlayer.module.scss';

export default function YouTubePlayer({ videoId = '' }: { videoId: string }) {
  const [playing, setPlaying] = useState<boolean>(false);
  const [eventTarget, setEventTarget] = useState<YouTubeEvent>();

  const onReady = (event: YouTubeEvent) => {
    if (!!event?.target) {
      setEventTarget(event)
    }
  };

  const onPlay = () => { setPlaying(true); };

  const onPause = (event: YouTubeEvent) => {
    const time = event.target.getCurrentTime();

    if (time === 0) {
      setPlaying(false);
    }
  };

  const onEnd = (event: YouTubeEvent) => {
    setPlaying(false);
    event.target.playVideo(0);
    event.target.pauseVideo();
  };

  const onClickToPlay = () => {
    if (!!eventTarget?.target?.playVideo) {
      !!eventTarget?.target?.playVideo(0)
    }
  };

  return !!videoId?.length && (
    <div className={styles.YouTubePlayer}>
      <YouTube
        videoId={videoId}
        onEnd={onEnd}
        onPause={onPause}
        onPlay={onPlay}
        onReady={onReady}
      />
      {!playing && !!onClickToPlay && (
        <button
          className={styles.play}
          type="button"
          aria-label="Executar o video"
          onClick={onClickToPlay}
        >
          <div
            className={styles.cover}
            style={{
              backgroundImage: `url(https://img.youtube.com/vi/${videoId}/0.jpg)`,
            }}
          />
          <PlayButtonIcon />
        </button>
      )}
    </div>
  );
};
