import React, { useState, useCallback, useEffect, useRef } from 'react';
import {
  SpeakerLoudIcon,
  SpeakerOffIcon,
  EnterFullScreenIcon,
  ExitFullScreenIcon,
} from '@radix-ui/react-icons';
import * as coursesAPI from '../../apis/coursesAPI';

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

const LiveNodePlayer = ({ url, courseCode, isAssistant, isShellWeb }) => {
  const divRef = useRef(null);
  const [dimensions, setDimensions] = useState({ width: 1920, height: 1080 });
  const [isMuted, setIsMuted] = useState(
    sessionStorage.getItem('token') === 'null' ||
      !sessionStorage.getItem('token')
      ? true
      : false,
  );
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [player, setPlayer] = useState(null);
  const [isLiveStreamNotStart, setIsLiveStreamNotStart] = useState(true);
  const script = document.createElement('script');
  const [intervalId, setIntervalId] = useState(null);
  const [courseStatusDescription, setcCourseStatusDescription] = useState('');
  const [isStartRecord, setIsStartRecord] = useState(true);

  const { t, i18n } = useTranslation();

  // 动态加载 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 });
        // 1000ms 后再次调整画面大小
        setTimeout(() => {
          newPlayer.onResize(0);
        }, 100);
      };
      newPlayer.play(true);
    } else {
      console.log('NodePlayer failed to load');
    }
    return newPlayer;
  }
  useEffect(() => {
    const id = setInterval(() => {
      // 定时器的逻辑
      getCourseInfo();
    }, 30000);

    setIntervalId(id);

    return () => {
      clearInterval(id);
    };
  }, []);

  /// 查询课程信息
  const getCourseInfo = async () => {
    const data = await coursesAPI.fetchCourseDetail(courseCode, 'course');
    console.log('%c Line:59 🍖 data', 'color:#2eafb0', data);
    if (data.Status === 2) {
      setcCourseStatusDescription(t('课程未开始，请稍后'));
    }
    if (data.Status === 4 && isLiveStreamNotStart) {
      setcCourseStatusDescription(t('老师暂时离开，请稍后'));
    }
    if (data.Status === 5) {
      setcCourseStatusDescription(t('课程已结束'));
      clearInterval(intervalId);
    }
    /// 如果助教正在录制 需要自动结束录制
    if (!isStartRecord) {
      endRecord();
    }
  };

  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(t('当前浏览器不支持全屏模式'));
    }
  };
  const startRecord = () => {
    setIsStartRecord(false);
    coursesAPI.sendCourseEntryNotice(`target=record?code=${courseCode}`);
  };
  const endRecord = () => {
    setIsStartRecord(true);
    coursesAPI.sendCourseEntryNotice(`target=endRecord?code=${courseCode}`);
  };

  return (
    <>
      <div
        id='node_player_video'
        className='nodeplayer-wrapper rounded-t overflow-hidden'>
        <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 flex justify-center items-center'
              style={{
                left: '40%',
                top: '40%',
                transform: 'Matrix4.translationValues(-50, -50, 0)',
              }}>
              <div className=' text-white pr-4'>{courseStatusDescription}</div>
              <LoadingOutlined
                style={{
                  fontSize: 64,
                  color: '#fff',
                }}
                spin
              />
            </div>
          )}
          {!isLiveStreamNotStart && isFullScreen && (
            <div className={'absolute bottom-0 w-full'}>{buildToolBar()}</div>
          )}
        </div>
      </div>

      {!isLiveStreamNotStart && !isFullScreen && (
        <div className='rounded-b overflow-hidden'>{buildToolBar()}</div>
      )}
      {/* 录制按钮 */}
      {isShellWeb && isAssistant && !isLiveStreamNotStart && (
        <div className='absolute top-0 right-0 mt-2 mr-2 flex'>
          {isStartRecord && (
            <button
              className='bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full'
              onClick={() => startRecord()}>
              {t('开始录制')}
            </button>
          )}
          {!isStartRecord && (
            <button
              className='bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 ml-2 rounded-full'
              onClick={() => endRecord()}>
              {t('结束录制')}
            </button>
          )}
        </div>
      )}
    </>
  );

  /// 功能按钮栏
  function buildToolBar() {
    return (
      <div className='flex justify-end bg-gray-900'>
        <button onClick={handleToggleMute} className='border-none p-1'>
          {!isMuted ? (
            <SpeakerLoudIcon className='text-gray-100 w-6 h-6' />
          ) : (
            <SpeakerOffIcon className='text-gray-100 w-6 h-6' />
          )}
        </button>
        <div className='w-2'></div>
        <button onClick={handleToggleFullScreen} className='border-none p-1'>
          {isFullScreen ? (
            <ExitFullScreenIcon className='text-gray-100 w-6 h-6' />
          ) : (
            <EnterFullScreenIcon className='text-gray-100 w-6 h-6' />
          )}
        </button>
      </div>
    );
  }
};

export default LiveNodePlayer;
