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

import { useCallStateHooks, VideoPreview } from '@stream-io/video-react-sdk';
import { motion } from 'motion/react';
import Stack from '@material-hu/mui/Stack';

const MotionStack = motion.create(Stack);

const CallerSelfView: FC = () => {
  const { useCameraState } = useCallStateHooks();
  const { mediaStream } = useCameraState();
  const wrapperRef = useRef<HTMLDivElement>(null);
  const [isVideoPlaying, setIsVideoPlaying] = useState(false);

  useEffect(() => {
    if (!mediaStream) return;
    const wrapper = wrapperRef.current;
    if (!wrapper) return;
    const video = wrapper.querySelector('video');
    if (!video) return;

    if (!video.paused && video.readyState >= 2) {
      setIsVideoPlaying(true);
      return;
    }

    const handlePlaying = () => setIsVideoPlaying(true);
    video.addEventListener('playing', handlePlaying);
    return () => video.removeEventListener('playing', handlePlaying);
  }, [mediaStream]);

  return (
    <MotionStack
      ref={wrapperRef}
      initial={{ opacity: 0 }}
      animate={{
        opacity: isVideoPlaying ? 1 : 0,
      }}
      transition={{ duration: 0.5, ease: 'easeOut' }}
      sx={{
        position: 'absolute',
        bottom: '24px',
        right: '24px',
        width: '339px',
        height: '210px',
        borderRadius: 1,
        overflow: 'hidden',
        '& .str-video__video-preview-container': {
          border: 'none',
          width: '100%',
          height: '100%',
        },
        '& .str_video__video-preview__disabled-video-preview': {
          display: 'none',
        },
        '& .str_video__video-preview__no-camera-preview': {
          display: 'none',
        },
      }}
    >
      <VideoPreview />
    </MotionStack>
  );
};

export default CallerSelfView;
