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

import FPlatformEnum from '../utils/enum';

import { useParams, useNavigate } from 'react-router-dom';
import CourseInformation from '../components/courses/CourseInformation';
import * as configAPI from '../apis/configAPI';
import * as coursesAPI from '../apis/coursesAPI';
import InteractiveArea from '../components/public/InteractiveArea';
import NomalTabs from '../components/public/NomalTabs';
import LiveNodePlayer from '../components/public/LiveNodePlayer';
import PlyrPlayer from '../components/public/PlyrPlayer';
import PdfPlayer from '../components/public/PdfPlayer';
import { useTranslation } from 'react-i18next';

import { ArrowLeftIcon } from '@radix-ui/react-icons';

const CoursePlayerPage = () => {
  const { courseCode, platform, token, language } = useParams();
  const { t, i18n } = useTranslation();

  const [courseData, setcourseData] = useState(null);
  const [courseFileUrl, setCourseFileUrl] = useState('');
  const [isShowPdf, setShowPdf] = useState(true);
  const [courseItems, setCourseItems] = useState([]);
  const [isShellWeb, setIsShellWeb] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [isIOS, setIsIOS] = useState(false);
  const [currentTab, setCurrentTab] = useState(t('简介'));
  const [isAssistant, setIsAssistant] = useState(false);
  const [tabsList, setTabsList] = useState([t('简介')]);
  // const [tabsList, setTabsList] = useState([t('简介'), t('资料')]);
  const navigate = useNavigate();
  const myVideoPlayerRef = useRef(null);
  const [heartBeatInterval, setHeartBeatInterval] = useState(30); // 心跳间隔，单位秒
  const golbalTimer = useRef(null);

  if (token) {
    sessionStorage.setItem('token', JSON.stringify(token));
  }

  const [plyrProps, setPlyrProps] = useState({
    source: {
      type: 'video',
      title: 'Example Video',
      sources: [
        {
          src: courseFileUrl,
          type: 'video/mp4',
          size: 720,
        },
      ],
    }, // https://github.com/sampotts/plyr#the-source-setter
    options: {
      playsinline: false,
    }, // https://github.com/sampotts/plyr#options
  });
  //   const [courseCatalogData, setCourseCatalogData] = useState(null);

  // 常量

  // 数据获取：课程数据
  const getCourseDeatil = useCallback(async () => {
    const data = await coursesAPI.fetchCourseDetail(courseCode, 'course');
    setcourseData(data);
    if (data.CourseType === 1) {
      setCourseFileUrl(data.CourseChannel.HttpPullUrl);
    } else {
      setCourseFileUrl(data.DefaultVideoToken);
    }
    if (data.IsAssistant) {
      setIsAssistant(true);
    }
    setCourseItems(data.CourseMaterials ?? []);
  }, [courseCode]);

  const getUserInfo = async () => {
    if (sessionStorage.getItem('token') !== 'null') {
      const { UserCode } = await coursesAPI.getUserInfo();
      sessionStorage.setItem('userCode', UserCode);
    }
  };

  // 初始化时记录播放次数
  const addCoursePlayCountOnInit = useCallback(async () => {
    await coursesAPI.addCoursePlayCountAsync(courseCode);
  }, [courseCode]);

  useEffect(() => {
    i18n.changeLanguage(language);
  }, [i18n, language]);

  useEffect(() => {
    addCoursePlayCountOnInit();
    getCourseDeatil();
    getUserInfo();
    if (isMobileDevice()) {
      setTabsList([t('简介'), t('互动区')]);
    }
  }, [getCourseDeatil, courseCode, addCoursePlayCountOnInit, t]);

  useEffect(() => {
    setShowPdf(courseFileUrl.endsWith('.pdf'));
    setPlyrProps({
      source: {
        type: 'video',
        title: 'Example Video',
        sources: [
          {
            src: courseFileUrl,
            type: 'video/mp4',
            size: 720,
          },
        ],
      },
      options: {
        autoplay: true,
        i18n: {
          speed: t('播放速度'),
          normal: t('正常'),
        },
      }, // https://github.com/sampotts/plyr#options
    });
  }, [courseFileUrl]);

  useEffect(() => {
    setIsShellWeb(FPlatformEnum.byIndex(platform).isShell());
    setIsMobile(FPlatformEnum.byIndex(platform).isMobile());
    setIsIOS(FPlatformEnum.byIndex(platform).isIos());
  }, [platform]);

  /// 发送一次心跳
  const sendHeartBeat = useCallback(async () => {
    const userCode = sessionStorage.getItem('userCode');
    // const userName = sessionStorage.getItem('userName');
    const data = await coursesAPI.visitorHeartRateAsync(courseCode, userCode);
    console.log('%c Line:74 🍉 data sendHeartBeat', 'color:#e50000', data);
  }, [courseCode]);

  /// 获取服务器配置然后写入心跳间隔
  useEffect(() => {
    const fetchConfig = async () => {
      let heartBeatSeconds = 30;
      try {
        await configAPI.getServerSettingAsync().then((response) => {
          setHeartBeatInterval(
            response.result.ServerConfigList.CourseVisitorHeartRateSeconds,
          );
          heartBeatSeconds =
            response.result.ServerConfigList.CourseVisitorHeartRateSeconds;
        });
        return heartBeatSeconds;
      } catch (error) {
        console.log('%c Line:106 🧀 error', 'color:#fca650', error);
        return heartBeatSeconds;
      }
    };
    /// 先获取配置，然后再发送心跳
    fetchConfig().then((heartBeatSeconds) => {
      heartBeatSeconds = checkInterval(heartBeatSeconds, 30);
      sendHeartBeat();
      console.log(' 🥛 开始发心跳 heartBeatSeconds', heartBeatSeconds);
      clearTimeout(golbalTimer.current);
      golbalTimer.current = setInterval(() => {
        sendHeartBeat();
      }, heartBeatSeconds * 1000);
    });
    return () => clearTimeout(golbalTimer.current);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  /// 校验心跳间隔，如果不符合则返回默认值，如果是 string 则尝试转换为 number，如果是 number 则判断大小
  const checkInterval = (i, min) => {
    if (typeof i === 'string') {
      i = parseInt(i);
    }
    if (typeof i !== 'number') {
      i = min;
    }
    if (i < min) {
      i = min;
    }
    return i;
  };

  // 交互事件
  // 切换 Tab
  const handleTabChange = (index) => {
    setCurrentTab(tabsList[index]);
  };
  const handleChildData = (data) => {
    setCourseFileUrl(data);
  };

  // 【课程列表】与【简介】Tab
  const buildTopTabs = () => {
    return (
      <NomalTabs
        className='w-100'
        tabs={tabsList}
        initTab={currentTab}
        onChangeTab={handleTabChange}></NomalTabs>
    );
  };
  // 返回课程列表
  const handleBackToCourseList = () => {
    //  myVideoPlayerRef.current.removeScriptChild();
    navigate(-1);
  };

  // 返回按钮
  function buildRouterBackIcon() {
    return (
      <button
        className='mb-3 w-10 h-10 text-sm rounded border md:border-0 md:hover:border border-gray-400'
        onClick={handleBackToCourseList}>
        <center>
          <ArrowLeftIcon className='text-gray-600 w-5 h-10' />
        </center>
      </button>
    );
  }
  const isMobileDevice = () => {
    return (
      typeof window.orientation !== 'undefined' ||
      navigator.userAgent.indexOf('IEMobile') !== -1
    );
  };

  // 内容主题区域，显示【课程列表】或【简介】
  const buildContentArea = () => {
    if (currentTab === t('简介')) {
      return (
        <div className='flex-grow flex flex-col  bg-gray-50 rounded p-5'>
          {/* <div className='text-xl mb-2'>{t('课程简介')}</div> */}
          <div className='text-sm text-gray-600 whitespace-pre-wrap'>
            {courseData == null || courseData.CourseIntro == null
              ? t('暂无简介')
              : courseData.CourseIntro}
          </div>
        </div>
      );
    } else if (currentTab === t('互动区')) {
      return (
        <div className='h-[60vh]'>
          <InteractiveArea h5courseCode={courseCode} />
        </div>
      );
    }
    return (
      <div className='flex flex-col  bg-gray-50 rounded'>
        <CourseInformation
          courseItems={courseItems}
          onChildData={handleChildData}
          platform={platform}
        />
      </div>
    );
  };

  return (
    <main className='flex min-h-screen flex-col p-5 h-full'>
      {sessionStorage.getItem('token') !== 'null' && buildRouterBackIcon()}
      <div className='flex-grow flex h-full '>
        {/* 视频播放器与PDF显示器 */}
        <div className={`h-full ${isMobileDevice() ? 'w-full' : 'w-3/4'}`}>
          {(courseData === null || courseData.CourseType !== 1) && (
            <div>
              {isShowPdf && (
                <div className={`h-[70vh]`}>
                  <PdfPlayer
                    courseFileUrl={courseFileUrl}
                    isShellWeb={isShellWeb}
                  />
                </div>
              )}
              {!isShowPdf && (
                <div className='border plyr-wrapper'>
                  <PlyrPlayer plyrProps={plyrProps} />
                </div>
              )}
            </div>
          )}

          {courseData != null && courseData.CourseType === 1 && (
            <div className='relative'>
              <LiveNodePlayer
                url={courseFileUrl}
                ref={myVideoPlayerRef}
                courseCode={courseData.Code}
                isAssistant={courseData.IsAssistant}
                isShellWeb={isShellWeb}
                isMobile={isMobile}
                isIOS={isIOS}
              />
            </div>
          )}
          {/* 课程简介 */}
          <div
            className={`mt-2 flex flex-col flex-grow ${
              isMobileDevice() ? 'w-[90vw]' : ''
            }`}>
            {buildTopTabs()}
            {buildContentArea()}
          </div>
        </div>

        {/* 互动交流区 暂时屏蔽*/}

        {!isMobileDevice() &&
        courseData != null &&
        courseData.CourseType === 1 ? (
          <div className='w-1/4 ml-5 border rounded h-[80vh]'>
            <InteractiveArea h5courseCode={courseCode} />
          </div>
        ) : (
          !isMobileDevice() && (
            <div className='w-1/4 ml-5 flex flex-col'>
              <div className='border rounded bg-gray-50 h-full text-xl flex flex-grow items-center justify-center'>
                <div className='text-lg text-gray-400'>
                  {t('互动区暂未开放')}
                </div>
              </div>
            </div>
          )
        )}
      </div>
    </main>
  );
};

export default CoursePlayerPage;
