import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import * as coursesAPI from '../../apis/coursesAPI';
import placeholderAvatarImageUrl from '../../assets/placeholder_avatar.png';
import { Pagination } from 'antd';

/// 创建成员列表模态框
export const OnlineMemberList = (param) => {
  const { courseCode } = param;
  const { t, i18n } = useTranslation();
  const [keyword, setKeyword] = useState(''); // 搜索关键词
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [displayMembers, setDisplayMembers] = useState([]);

  // 分页功能
  const handleChangePage = (page) => {
    setCurrentPage(page);
  };

  const handleSearch = (e) => {
    console.log('%c Line:20 🍇 handleSearch', 'color:#f5ce50', 'handleSearch');
    setKeyword(e.target.value);
  };

  const handleRefresh = async () => {
    console.log(
      '%c Line:20 🍇 handleRefresh',
      'color:#f5ce50',
      'handleRefresh',
    );
    setKeyword('');
    let members = await searchMembers(
      currentPage,
      pageSize,
      keyword,
      courseCode,
    );
    console.log('%c Line:29 🥕 members', 'color:#2eafb0', members);
    setDisplayMembers(members);
  };

  // 每次搜索文本或页码改变时，更新分页器
  useEffect(() => {
    async function fetchData() {
      let members = await searchMembers(
        currentPage,
        pageSize,
        keyword,
        courseCode,
      );
      console.log('%c Line:29 🥕 members', 'color:#2eafb0', members);
      setDisplayMembers(members);
    }
    fetchData();
  }, [currentPage, pageSize, keyword, courseCode]);

  /// 发送搜索请求
  async function searchMembers(currentPage, pageSize, keyword, courseCode) {
    // console.log('%c Line:32 🥕 keyword', 'color:#b03734', keyword);
    // console.log('%c Line:32 🍣 pageSize', 'color:#42b983', pageSize);
    // console.log('%c Line:32 🍔 currentPage', 'color:#2eafb0', currentPage);
    // console.log(
    //   '%c Line:33 🍇 searchMembers',
    //   'color:#f5ce50',
    //   'searchMembers',
    // );
    let response = await coursesAPI.queryCourseBrowsedRecordsAsync(
      currentPage,
      pageSize,
      courseCode,
      keyword,
    );

    console.log('%c Line:43 🍬 response', 'color:#33a5ff', response);

    let result = response.result;

    setTotal(result.TotalCount);

    let members = [];
    if (result.PageData.length > 0) {
      members = result.PageData.map((item) => {
        return {
          id: item.UserCode,
          name: item.DisplayName,
          avatarUrl: item.Avatar,
          isOnline: item.IsOnline,
          role: item.BrowsedUserType,
        };
      });
    }
    return members;
  }

  return (
    <div className=' h-[80vh] flex flex-col'>
      <div className=' flex justify-between'>
        <input
          className='border-gray-400 border rounded-md p-2 mr-2 h-8'
          placeholder={t('搜索成员')}
          value={keyword}
          onChange={handleSearch}
        />
        <div
          className='hover:bg-gray-100 cursor-pointer flex items-center justify-center rounded-md text-gray-500 border-gray-400 border w-16'
          onClick={handleRefresh}>
          {t('刷新')}
        </div>
      </div>

      <div className='mt-4 flex-grow overflow-y-auto'>
        {displayMembers.length > 0 ? (
          displayMembers.map((member) => (
            <div
              key={member.id}
              className='flex flex-row p-2 border-b border-gray-300'>
              <img
                className='rounded-full w-10 h-10 mr-2'
                src={member.avatarUrl || placeholderAvatarImageUrl}
                alt={member.name}
              />
              <div className='flex flex-col'>
                <span className='font-medium'>{member.name || '未知'}</span>
                {buildOnlineTag(member.isOnline)}
              </div>
              <div className='flex-grow'></div>
              <div className='flex flex-col'>{buildRoleTag(member.role)}</div>
            </div>
          ))
        ) : (
          <div className='flex items-center justify-center p-4'>
            <p className='text-gray-400'>{t('暂无数据')}</p>
          </div>
        )}
      </div>
      <div className='mt-4 flex justify-center'>
        <Pagination
          size='small'
          current={currentPage}
          pageSize={pageSize}
          total={total}
          onChange={handleChangePage}
        />
      </div>
    </div>
  );

  // 构建角色标签
  function buildRoleTag(role) {
    switch (role) {
      case 0:
        return (
          <span className='px-2 rounded-md bg-orange-100 text-orange-600 border-orange-400 border'>
            {t('讲师')}
          </span>
        );
      case 1:
        return (
          <span className='px-2 rounded-md bg-green-100 text-green-600 border-green-400 border '>
            {t('助教')}
          </span>
        );
      case 2:
        return (
          <span className='px-2 rounded-md bg-blue-100 text-blue-600 border-blue-400 border'>
            {t('嘉宾')}
          </span>
        );
      case 3:
        return (
          <span className='px-2 rounded-md bg-blue-100 text-blue-600 border-blue-400 border'>
            {t('成员')}
          </span>
        );
      default:
        return (
          <span className='px-2 rounded-md bg-gray-100 text-gray-500 border-gray-400 border'>
            {t('游客')}
          </span>
        );
    }
  }

  // 构建在线状态标签
  function buildOnlineTag(isOnline) {
    return isOnline ? (
      <span className='text-green-500 '>{t('在线')}</span>
    ) : (
      <span className='text-gray-500 '>{t('离线')}</span>
    );
  }
};
