import { observer } from 'mobx-react-lite';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import ReactPlayer from 'react-player';

import { useStores } from '@/app/(root)/AppProviders';

interface VideoPlayerProps {
  videoUrl?: string | null;
  imageUrl?: string | null;
  className?: string;
  isCurrentSong?: boolean;
  onClick?: (e: any) => any;
}

const PLAYBAR_SYNC_THRESHOLD = 1;

const PlaybarSyncVideoPlayer: React.FC<VideoPlayerProps> = observer(
  ({ className, onClick, videoUrl, isCurrentSong, imageUrl }) => {
    if (!videoUrl) return null;

    const { playbar } = useStores();

    const isPlaying = isCurrentSong && playbar.isPlaying;
    const isSeeking = playbar.isDragging;

    const videoPlayer = useRef<ReactPlayer>(null);
    const [videoDuration, setVideoDuration] = useState(1);
    const syncVideoTime = useCallback(() => {
      // Video is looping - seek to playbar current time mod video duration
      videoPlayer.current?.seekTo(playbar.currentTime % videoDuration);
    }, [videoDuration]);

    useEffect(() => {
      if (isPlaying) {
        videoPlayer.current?.forceUpdate();
      }
    }, [isPlaying]);

    useEffect(() => {
      if (!isCurrentSong) {
        return;
      }
      const videoCurrTime = videoPlayer.current?.getCurrentTime();
      const videoSyncedTime = playbar.currentTime % videoDuration;

      if (videoCurrTime) {
        // Calculate the difference, accounting for wrap-around
        const timeDifference = Math.min(
          Math.abs(videoSyncedTime - videoCurrTime),
          videoDuration - Math.abs(videoSyncedTime - videoCurrTime)
        );

        if (timeDifference > PLAYBAR_SYNC_THRESHOLD) {
          syncVideoTime();
        }
      }
    }, [isCurrentSong, playbar.currentTime]);

    return (
      <ReactPlayer
        className={className}
        onClick={onClick}
        ref={videoPlayer}
        url={videoUrl}
        light={(!isPlaying && imageUrl) || false}
        playing={isPlaying && !isSeeking}
        volume={0}
        muted={true}
        width='100%'
        height='100%'
        playIcon={<></>}
        onPlay={syncVideoTime}
        loop={true}
        onDuration={setVideoDuration}
        playsinline={true}
        config={{
          file: {
            attributes: {
              style: {
                objectFit: 'cover',
                width: '100%',
                height: '100%',
                borderRadius: '5%',
              },
              poster: imageUrl,
            },
          },
        }}
      />
    );
  }
);

export default PlaybarSyncVideoPlayer;
