import React, { useEffect, useRef, useState } from 'react';
import { focusEditor, useEditorRef } from '@udecode/plate-common';
import videojs from 'video.js';

import 'video.js/dist/video-js.css';

interface IVideoPlayerProps {
  elementRef: React.RefObject<HTMLDivElement>;
  url: string;
}

export function VideoPlayer({ elementRef, url }: IVideoPlayerProps) {
  const videoRef = useRef(null);
  const playerRef = useRef<any>(null);
  const [option, setOptopm] = useState({});

  const editor = useEditorRef();

  const onReadyPlay = (palyer: any) => {
    videoRef.current = palyer;
    palyer.play();
  };

  const init = () => {
    const _option = {
      width: 500,
      height: 300,
      controls: true, // 是否显示控制条
      poster: '', // 视频封面图地址,记住这一点poster是绝对地址，如果给相对位置会请求到你封装的地址中去，向封装的地址发起请求。
      preload: 'auto',
      autoplay: false,
      fluid: true, // 自适应宽高，也可以设置为常见比例"4:3"，"16:9"
      language: 'zh-CN', // 设置语言
      muted: false, // 是否静音
      liveDisplay: true, // 直播提示
      inactivityTimeout: false,
      playbackRates: [0.5, 1, 1.5, 2],
      controlBar: {
        // 设置控制条组件
        currentTimeDisplay: true,
        timeDivider: true,
        durationDisplay: true,
        /* 使用children的形式可以控制每一个控件的位置，以及显示与否 */
        children: [
          { name: 'playToggle' }, // 播放按钮
          { name: 'currentTimeDisplay' }, // 当前已播放时间
          { name: 'progressControl' }, // 播放进度条
          {
            name: 'remainingTimeDisplay',
            //是否显示剩余时间，默认为true
            displayNegative: true,
          },
          { name: 'durationDisplay' }, // 总时间
          {
            name: 'volumePanel', // 音量控制
            inline: false, // 不使用水平方式
          },
          {
            name: 'pictureInPictureToggle', //支持画中画
          },
          { name: 'FullscreenToggle' }, // 全屏
          {
            // 倍数播放
            name: 'playbackRateMenuButton',
            playbackRates: [0.5, 1, 1.5, 2, 2.5],
          },
        ],
      },
    };
    setOptopm(_option);

    if (!playerRef.current) {
      const videoElement = videoRef.current;
      if (!videoElement) return;

      const player = (playerRef.current = videojs(
        videoElement,
        _option,
        () => {}
      ));
      onReadyPlay(player);
    }
  };

  useEffect(() => {
    init();
  }, []);

  return (
    <div className="video_play">
      <video
        ref={videoRef}
        src={url}
        onFocus={() => {
          elementRef.current?.click();
          focusEditor(editor);
        }}
        onClick={(e) => e.preventDefault()}
        controls
        controlsList="nodownload"
        className="video-js vjs-big-play-centered vjs-hqcat"
      />
    </div>
  );
}
