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 coursesAPI from '../apis/coursesAPI';
import InteractiveArea from '../components/public/InteractiveArea';
import NomalTabs from '../components/public/NomalTabs';
import LiveNodePlayer from '../components/public/LiveNodePlayer';
import MediaPlayer from '../components/public/MediaPlayer';
import PdfPlayer from '../components/public/PdfPlayer';

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

const VideoCoursePlayerPage = () => {
  const { courseCode, platform, token } = useParams();
  const [courseData, setcourseData] = useState(null);
  const [courseFileUrl, setCourseFileUrl] = useState('');
  const [isShowPdf, setShowPdf] = useState(true);
  const [courseItems, setCourseItems] = useState([]);
  const [isShellWeb, setIsShellWeb] = useState(false);
  const [currentTab, setCurrentTab] = useState('简介');
  const [isAssistant, setIsAssistant] = useState(false);
  const [tabsList, setTabsList] = useState(['简介', '资料']);
  const [isStartRecord, setIsStartRecord] = useState(true);
  const navigate = useNavigate();
  const myVideoPlayerRef = useRef(null);

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

  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(() => {
    addCoursePlayCountOnInit();
    getCourseDeatil();
    getUserInfo();
    if (isMobileDevice()) {
      setTabsList(['简介', '资料', '互动区']);
    }
  }, [getCourseDeatil, courseCode]);

  useEffect(() => {
    setShowPdf(courseFileUrl.endsWith('.pdf'));
    setPlyrProps({
      source: {
        type: 'video',
        title: 'Example Video',
        sources: [
          {
            src: courseFileUrl,
            type: 'video/mp4',
            size: 720,
          },
        ],
      },
      options: {
        autoplay: true,
      },
    });
  }, [courseFileUrl]);

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

  // 交互事件
  // 切换 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 startRecord = () => {
    setIsStartRecord(false);
    coursesAPI.sendCourseEntryNotice(`target=record?code=${courseData.Code}`);
  };
  const endRecord = () => {
    setIsStartRecord(true);
    coursesAPI.sendCourseEntryNotice(
      `target=endRecord?code=${courseData.Code}`,
    );
  };

  // 内容主题区域，显示【课程列表】或【简介】
  const buildContentArea = () => {
    if (currentTab === '简介') {
      return (
        <div className='flex-grow flex flex-col  bg-gray-50 rounded p-5'>
          <div className='text-xl mb-2'>课程简介</div>
          <div className='text-sm text-gray-600 whitespace-pre-wrap'>
            {courseData == null || courseData.CourseIntro == null
              ? '暂无简介'
              : courseData.CourseIntro}
          </div>
        </div>
      );
    } else if (currentTab === '互动区') {
      return (
        <div className=' h-full'>
          <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'>
                  <MediaPlayer plyrProps={plyrProps} />
                </div>
              )}
            </div>
          )}

          {courseData != null && courseData.CourseType === 1 && (
            <div className='relative'>
              <LiveNodePlayer url={courseFileUrl} ref={myVideoPlayerRef} />
              {/* 录制按钮 */}
              {isShellWeb && courseData.IsAssistant && (
                <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()}>
                      开始录制
                    </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()}>
                      结束录制
                    </button>
                  )}
                </div>
              )}
            </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'>
            <InteractiveArea courseCode={courseCode} />
          </div>
        ) : (
          <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'>互动区暂未开放</div>
            </div>
          </div>
        )}
      </div>
    </main>
  );
};

export default VideoCoursePlayerPage;
