import InteractiveArea from '../components/public/InteractiveArea';
import React, { useState, useEffect } from 'react';
import * as coursesAPI from '../apis/coursesAPI';
import { OnlineMemberList } from '../components/public/OnlineMemberList';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
import { Modal as AntdModal } from 'antd';

// 讨论区
export default function DiscussionBoardPage() {
  const { courseCode, token, language } = useParams();
  const { t, i18n } = useTranslation();
  const [isShowModal, setIsShowModal] = useState(false); // 是否展示课程模态框
  const [onlineCount, setOnlineCount] = useState(0); // 在线人数

  useEffect(() => {
    /// 刷新消息
    const fetchData = async () => {
      let response = await coursesAPI.queryCourseBrowsedCountAsync(courseCode);
      try {
        setOnlineCount(response.result.OnlineCount);
      } catch (error) {
        console.log('%c Line:23 🍰 error', 'color:#e41a6a', error);
      }
    };
    fetchData();
    const intervalId = setInterval(fetchData, 5000);
    return () => clearInterval(intervalId);
  }, [courseCode]);

  /// 立即刷新在线人数
  const handleRefreshOnlineCount = async () => {
    let response = await coursesAPI.queryCourseBrowsedCountAsync(courseCode);
    try {
      setOnlineCount(response.result.OnlineCount);
    } catch (error) {
      console.log('%c Line:23 🍰 error', 'color:#e41a6a', error);
    }
  };

  const handleCloseCreateCourseModal = () => {
    setIsShowModal(false);
  };
  return (
    <main className='h-screen flex flex-col'>
      <div
        className='bg-white text-sm p-2 hover:text-blue-500 cursor-pointer'
        onClick={() => {
          setIsShowModal(true);
          handleRefreshOnlineCount();
        }}>
        {t('成员列表')}
      </div>
      <div className='h-full min-h-0'>
        <InteractiveArea />
      </div>
      <OnlineMemberListModal
        courseCode={courseCode}
        isOpen={isShowModal}
        onRequestClose={handleCloseCreateCourseModal}></OnlineMemberListModal>
    </main>
  );
}

/// 创建成员列表模态框
const OnlineMemberListModal = ({ courseCode, isOpen, onRequestClose }) => {
  const { t, i18n } = useTranslation();

  const handleCloseModal = () => {
    onRequestClose();
  };

  return (
    <AntdModal
      open={isOpen}
      destroyOnClose={true}
      title={t('成员列表')}
      style={{ top: 0, height: '50%' }}
      onCancel={handleCloseModal}
      // width={850}
      footer={null}>
      <OnlineMemberList courseCode={courseCode} />
    </AntdModal>
  );
};
