import React, { useEffect, useRef, useState } from 'react';
import { MediaProps } from '../Media';
import { VideoWrap } from './VideoWrap';
import { jsonProxy2, revokeJsonProxy } from '@/utils/constants';

const Video: React.FC<MediaProps> = ({
  media,
  autoPlay,
  mediaVisible,
  getMedia,
  cssStyle = '',
}) => {
  const [hasChangedProxy, setHasChangedProxy] = useState(false);
  const [hasRemovedProxy, setHasRemovedProxy] = useState(false);
  const video = useRef<HTMLVideoElement>(null);
  useEffect(() => {
    getMedia?.(video.current);
  }, [autoPlay, getMedia]);

  return (
    <VideoWrap cssStyle={cssStyle}>
      <video
        src={media}
        ref={video}
        autoPlay={autoPlay}
        controls={Boolean(mediaVisible)}
        className="video"
        loop
        playsInline
        onError={el => {
          if (!hasRemovedProxy) {
            el.currentTarget.src = revokeJsonProxy(el.currentTarget.src);
            const el2 = el.currentTarget;
            const pNode = el.currentTarget.parentNode;
            el.currentTarget.remove();
            pNode?.append(el2);
            setHasRemovedProxy(true);
          } else if (!hasChangedProxy) {
            el.currentTarget.src = jsonProxy2(el.currentTarget.src);
            const el2 = el.currentTarget;
            const pNode = el.currentTarget.parentNode;
            el.currentTarget.remove();
            pNode?.append(el2);
            setHasChangedProxy(true);
          }
        }}
      >
        <source
          src={media}
          onError={el => {
            if (!hasRemovedProxy) {
              el.currentTarget.src = revokeJsonProxy(el.currentTarget.src);
              const el2 = el.currentTarget;
              const pNode = el.currentTarget.parentNode;
              el.currentTarget.remove();
              pNode?.append(el2);
              setHasRemovedProxy(true);
            } else if (!hasChangedProxy) {
              el.currentTarget.src = jsonProxy2(el.currentTarget.src);
              const el2 = el.currentTarget;
              const pNode = el.currentTarget.parentNode;
              el.currentTarget.remove();
              pNode?.append(el2);
              setHasChangedProxy(true);
            }
          }}
        />
      </video>
    </VideoWrap>
  );
};

export default Video;
