import React, { useState, useCallback, useEffect, useRef } from 'react';

import { LivePlayer } from '../../js/device_live/player';
import { LoadingOutlined } from '@ant-design/icons';

const LiveNodePlayer = ({ url }) => {
  const divRef = useRef(null);
  const [dimensions, setDimensions] = useState({ width: 1920, height: 1080 });
  const [isMuted, setIsMuted] = useState(
    sessionStorage.getItem('token') === 'null' ? true : false,
  );
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [player, setPlayer] = useState(null);
  const [isLiveStreamNotStart, setIsLiveStreamNotStart] = useState(true);
  const script = document.createElement('script');

  // 动态加载 NodePlayer.min.js 脚本
  useEffect(() => {
    script.src =
      process.env.PUBLIC_URL + '/node_player/0.12.6/NodePlayer.min.js';
    script.async = true;
    let _nodePlayer;
    try {
      // 检查 NodePlayer 是否加载成功
      script.onload = async () => {
        _nodePlayer = await _loadPlayer();
        setPlayer(_nodePlayer);
      };
      if (typeof NP_LOGLEVEL === 'undefined') {
        document.head.appendChild(script);
      } else {
        (async () => {
          _nodePlayer = await _loadPlayer();
          setPlayer(_nodePlayer);
        })();
      }
    } catch (err) {
      console.log('%c Line:90 👾 err', 'color:#33a5ff', err);
    }
  }, []);

  useEffect(() => {
    if (player) {
      const resizeObserver = new ResizeObserver((entries) => {
        window.requestAnimationFrame(() => {
          player.onResize(0);
        });
      });
      const currentDiv = divRef.current;
      if (currentDiv) {
        resizeObserver.observe(currentDiv);
      }
      return () => {
        if (resizeObserver && currentDiv) {
          resizeObserver.unobserve(currentDiv);
        }
        if (player) {
          player.stop();
          player.releasePlayer();
        }
      };
    }
  }, [player]);

  async function _loadPlayer() {
    let newPlayer;

    if (window.NodePlayer !== undefined) {
      await LivePlayer.init();
      newPlayer = new LivePlayer('mian_canvas', url);
      // newPlayer = new LivePlayer(
      //   'mian_canvas',
      //   'https://liveplay.fis.plus/live/v7cdichfai7wibnfwmt0v38fzk.flv',
      // );
      newPlayer.onError = function (state) {
        setIsLiveStreamNotStart(true);
      };

      newPlayer.onPlay = function () {
        setIsLiveStreamNotStart(false);
      };
      newPlayer.onInfo = function ({ width, height }) {
        setDimensions({ width, height });
      };
      newPlayer.play(true);
    } else {
      console.log('NodePlayer failed to load');
    }
    return newPlayer;
  }

  const handleToggleMute = () => {
    setIsMuted(!isMuted);
    player.audioResume();
    player.enableAudio(isMuted);
    // event.stopPropagation()
  };

  const onFullScreenChange = useCallback(() => {
    const isFS = document.fullscreenElement !== null;
    setIsFullScreen(isFS);
  }, []);

  useEffect(() => {
    document.addEventListener('fullscreenchange', onFullScreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', onFullScreenChange);
    };
  }, [onFullScreenChange]);

  const handleToggleFullScreen = () => {
    setIsFullScreen(!isFullScreen);
    const main = document.getElementById('node_player_video');
    if (document.fullscreenEnabled) {
      if (!isFullScreen) {
        main.requestFullscreen();
      } else {
        document.exitFullscreen();
      }
    } else {
      console.log('当前浏览器不支持全屏模式');
    }
  };

  return (
    <div id='node_player_video'>
      <div id='main'>
        <canvas
          id='mian_canvas'
          ref={divRef}
          style={{ resize: 'both', overflow: 'auto', backgroundColor: 'black' }}
          className='h-full w-full'
          width={dimensions.width}
          height={dimensions.height}></canvas>
        {isLiveStreamNotStart && (
          <div className='absolute inset-0 flex items-center justify-center '>
            <LoadingOutlined
              style={{
                fontSize: 64,
                color: '#fff',
              }}
              spin
            />
          </div>
        )}
        {!isLiveStreamNotStart && (
          <div className='flex justify-end bg-black text-white'>
            <button onClick={handleToggleMute} className='border-none p-1'>
              {!isMuted ? (
                <img
                  src={process.env.PUBLIC_URL + '/openSound.svg'}
                  className='text-white w-10'
                  alt='开始声音'
                />
              ) : (
                <img
                  src={process.env.PUBLIC_URL + '/closeSound.svg'}
                  className='text-white w-10'
                  alt='关闭声音'
                />
              )}
            </button>
            <div className='w-5'></div>
            <button
              onClick={handleToggleFullScreen}
              className='border-none p-1'>
              {isFullScreen ? (
                <img
                  src={process.env.PUBLIC_URL + '/cancelFullScreen.svg'}
                  className='text-white w-10'
                  alt='取消全屏'
                />
              ) : (
                <img
                  src={process.env.PUBLIC_URL + '/fullScreen.svg'}
                  className='text-white w-10'
                  alt='全屏'
                />
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default LiveNodePlayer;
