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

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

import { useParams } 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 { Modal, Input, message } from 'antd';
import { useTranslation } from 'react-i18next';

const GuestCoursePlayerPage = () => {
  const { courseCode, language } = 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 [tabsList, setTabsList] = useState(['简介', '资料']);
  const [userName, setUserName] = useState('');
  const [messageApi, contextHolder] = message.useMessage();
  const { t, i18n } = useTranslation();
  const [isGuestNameModalOpen, setIsGuestNameModalOpen] = useState(
    !sessionStorage.getItem('userName'),
  );

  const myVideoPlayerRef = useRef(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);
    console.log('%c Line:58 🎂 data', 'color:#ed9ec7', data);
    if (data.CourseType === 1) {
      setCourseFileUrl(data.CourseChannel.HttpPullUrl);
    } else {
      setCourseFileUrl(data.DefaultVideoToken);
    }
    setCourseItems(data.CourseMaterials ?? []);
  }, [courseCode]);

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

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

  useEffect(() => {
    addCoursePlayCountOnInit();
    getCourseDeatil();
    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]);

  // 交互事件
  // 切换 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 isMobileDevice = () => {
    return (
      typeof window.orientation !== 'undefined' ||
      navigator.userAgent.indexOf('IEMobile') !== -1
    );
  };

  const inputChange = (e) => {
    console.log('%c Line:146 🍐 e.target', 'color:#fca650', e.target);
    setUserName(e.target.value.trim());
  };
  const enterCourse = () => {
    console.log('%c Line:152 🌰 userName', 'color:#e41a6a', userName);

    if (userName !== '') {
      sessionStorage.setItem('userName', userName);
      setIsGuestNameModalOpen(false);
    } else {
      messageApi.open({
        type: 'error',
        content: '请输入用户姓名',
      });
    }
  };

  // 内容主题区域，显示【课程列表】或【简介】
  const buildContentArea = () => {
    if (currentTab === '简介') {
      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-full'>
          <InteractiveArea h5courseCode={courseCode} isGuest={true} />
        </div>
      );
    }
    return (
      <div className='flex flex-col  bg-gray-50 rounded'>
        <CourseInformation
          courseItems={courseItems}
          onChildData={handleChildData}
        />
      </div>
    );
  };

  return (
    <main className='flex min-h-screen flex-col p-5 h-full'>
      {contextHolder}
      <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}
                courseCode={courseData.Code}
                isAssistant={courseData.IsAssistant}
                isShellWeb={isShellWeb}
              />
            </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} isGuest={true} />
          </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'>{t('互动区暂未开放')}</div>
            </div>
          </div>
        )}
      </div>
      <Modal
        title='请输入姓名'
        open={isGuestNameModalOpen}
        centered
        maskClosable={false}
        mask={true}
        closable={false}
        destroyOnClose={true}
        footer={null}
        bodyStyle={{ width: '100%' }}>
        <div className='w-full max-w-md p-6 bg-white rounded-lg '>
          <form>
            <div className='mb-8 '>
              <Input placeholder='请输入姓名' onChange={inputChange} />
            </div>
            <div className='flex justify-center items-center w-full'>
              <button
                className='bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline'
                type='button'
                onClick={enterCourse}>
                {t('进入课程')}
              </button>
            </div>
          </form>
        </div>
      </Modal>
    </main>
  );
};

export default GuestCoursePlayerPage;
