import React, { useState, useCallback, useEffect, useRef } from 'react';
import { message } from 'antd';
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,
  isMobile,
  isIOS,
}) => {
  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 [recording, setRecording] = useState(false);

  const { t, i18n } = useTranslation();

  // 动态加载 NodePlayer.min.js 脚本
  useEffect(() => {
    script.src = './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);
    }
    return () => {
      if (recording) {
        endRecord();
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  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('课程已结束'));
      if (recording) {
        endRecord();
      }
      clearInterval(intervalId);
    }
  };

  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 = () => {
    if (isIOS) {
      iosFullScreen();
      return;
    }
    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 = () => {
    if (isLiveStreamNotStart) {
      message.error(t('直播未开始，不能录制'));
      return;
    }
    setRecording(true);
    coursesAPI.sendCourseEntryNotice(`target=record?code=${courseCode}`);
  };
  const endRecord = () => {
    setRecording(false);
    coursesAPI.sendCourseEntryNotice(`target=endRecord?code=${courseCode}`);
  };
  const openStorageDir = () => {
    coursesAPI.sendCourseEntryNotice(`target=openStorageDir`);
  };
  const iosFullScreen = () => {
    coursesAPI.sendCourseEntryNotice(
      `target=openIOSFullScreenPlayer?url=${url}`,
    );
  };

  return (
    <div
      id='node_player_video'
      className={isFullScreen ? 'w-screen h-screen' : ''}>
      <div
        className={
          isFullScreen
            ? 'nodeplayer-wrapper-fullscreen'
            : '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 flex-col justify-center items-center top-1/2 left-1/2 -translate-x-1/2  -translate-y-1/2'>
              <div className=' text-white mb-10'>{courseStatusDescription}</div>
              <LoadingOutlined
                style={{
                  fontSize: 48,
                  color: '#fff',
                }}
                spin
              />
            </div>
          )}
          {isFullScreen && (
            <div className={'absolute bottom-0 w-full group'}>
              {buildToolBar()}
            </div>
          )}
        </div>
      </div>
      {!isFullScreen && (
        <div className='rounded-b overflow-hidden'>{buildToolBar()}</div>
      )}
    </div>
  );

  // FIXME 移动端全屏按钮需要显示

  /// 功能按钮栏
  function buildToolBar() {
    var style =
      'group-hover:translate-y-0 group-hover:delay-0 delay-500 translate-y-10 duration-300';
    if (isMobile) {
      style = 'translate-y-0';
    }
    return (
      <div className={isFullScreen ? style : ''}>
        <div className='flex justify-between bg-gray-900  '>
          {buildRecordButton()}
          <div className='flex justify-end '>
            {/* <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>
        </div>
      </div>
    );
  }

  /// 构建录制按钮
  function buildRecordButton() {
    if (isShellWeb && isAssistant) {
      return (
        <div className='flex'>
          {!recording && (
            <button
              className='bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-4'
              onClick={() => startRecord()}>
              {t('开始录制')}
            </button>
          )}
          {recording && (
            <button
              className='bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4'
              onClick={() => endRecord()}>
              {t('结束录制')}
            </button>
          )}
          <a
            className='text-white py-2 px-4 cursor-pointer hover:underline'
            onClick={() => openStorageDir()}>
            {t('查看录制文件')}
          </a>
        </div>
      );
    } else {
      return <div></div>;
    }
  }
};

export default LiveNodePlayer;
