import React, { useState, useCallback, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import * as coursesAPI from '../apis/coursesAPI';
import NomalTabs from '../components/public/NomalTabs';
import PlyrPlayer from '../components/public/PlyrPlayer';
import { useTranslation } from 'react-i18next';
import { ArrowLeftIcon } from '@radix-ui/react-icons';

const WechatCourseDetailPage = () => {
  const { courseCode, language } = useParams();
  const { t, i18n } = useTranslation();

  const [courseData, setcourseData] = useState(null);
  const [courseFileUrl, setCourseFileUrl] = useState('');
  const [currentTab, setCurrentTab] = useState(t('简介'));
  const [tabsList, setTabsList] = useState([t('简介')]);
  const navigate = useNavigate();

  const [plyrProps, setPlyrProps] = useState({
    source: {
      type: 'video',
      title: '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 getCourseDeatil = useCallback(async () => {
    const data = await coursesAPI.fetchCourseDetail(courseCode, 'course');
    setcourseData(data);
    if (data.CourseType === 1) {
      setCourseFileUrl(data.CourseChannel.HttpPullUrl);
    } else {
      setCourseFileUrl(data.DefaultVideoToken);
    }
  }, [courseCode]);

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

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

  useEffect(() => {
    setPlyrProps({
      source: {
        type: 'video',
        title: 'Video',
        sources: [
          {
            src: courseFileUrl,
            type: 'video/mp4',
            size: 720,
          },
        ],
      },
      options: {
        autoplay: true,
        controls: [
          'play',
          'progress',
          'current-time',
          'mute',
          'settings',
          'fullscreen',
        ],
        i18n: {
          speed: t('播放速度'),
          normal: t('正常'),
        },
        speed: {
          selected: 1,
          options: [2, 1.5, 1.25, 1, 0.5],
        },
        fullscreen: {
          enabled: true,
          iosNative: true,
        },
        playsinline: true,
      }, // https://github.com/sampotts/plyr#options
    });
  }, [courseFileUrl, t]);

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

  // 【课程列表】与【简介】Tab
  const buildTopTabs = () => {
    return (
      <NomalTabs
        className='w-100'
        tabs={tabsList}
        initTab={currentTab}
        onChangeTab={handleTabChange}></NomalTabs>
    );
  };
  // 返回课程列表
  const handleBackToCourseList = () => {
    // 关闭当前窗口
    window.close();
    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 = () => {
    <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>;
  };

  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 '>
        <div className={`h-full ${isMobileDevice() ? 'w-full' : 'w-3/4'}`}>
          {(courseData === null || courseData.CourseType !== 1) && (
            <div>
              <div className='border plyr-wrapper'>
                <PlyrPlayer plyrProps={plyrProps} />
              </div>
            </div>
          )}
          {/* 课程标题 */}
          <div className='text-xl mt-10 font-bold'>{courseData?.Name}</div>

          {/* 课程简介 */}
          <div
            className={`mt-2 flex flex-col flex-grow ${
              isMobileDevice() ? 'w-[90vw]' : ''
            }`}>
            {buildTopTabs()}
            {buildContentArea()}
          </div>
        </div>
      </div>
    </main>
  );
};

export default WechatCourseDetailPage;
