import React, { useState, useCallback, useEffect } from 'react';
import DataListWithPagination from '../components/courses/DataListWithPagination';
import RouterBackButton from '../components/public/RouterBackButton';
import SearchBar from '../components/public/SearchBar';
import Spacer from '../components/public/Spacer';
import { useParams } from 'react-router-dom';
import { useSessionStorage } from 'react-use';
import * as coursesAPI from '../apis/coursesAPI';
// import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import FPlatformEnum from '../utils/enum';
import Loading from '../components/public/Loading';

// 查看更多 -> 全部课程
export default function AllCoursesPage() {
  const { token, platform, language } = useParams();
  const subsetTab = 'course';
  // const navigate = useNavigate();
  const { t, i18n } = useTranslation();

  const [kPlatform, setKPlatform] = useSessionStorage(
    'platform',
    platform || FPlatformEnum.web.index,
  );

  const [kToken, setKToken] = useSessionStorage('token', token);

  const [coursesData, setCoursesData] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [searchInput, setSearchInput] = useState(''); // 用于显示，不用于查询
  const [searchKeyword, setSearchKeyword] = useState(''); // 用于查询
  const [fetching, setFetching] = useState(false); // 数据查询状态

  useEffect(() => {
    setKToken(token);
  }, [token, setKToken]);

  useEffect(() => {
    setKPlatform(platform);
  }, [platform, setKPlatform]);

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

  const getCourses = useCallback(async () => {
    setFetching(true);
    const data = await coursesAPI.fetchLiveCoursesData(
      currentPage,
      searchKeyword,
    );
    setFetching(false);
    setCoursesData(data.result);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, searchKeyword, kToken]);

  useEffect(() => {
    getCourses();
  }, [getCourses]);

  useEffect(() => {
    // console.log(kPlatform);
  }, [kPlatform]);

  useEffect(() => {
    console.log('token ' + kToken);
  }, [kToken]);

  const handleSearchChange = (event) => {
    setSearchInput(event.target.value);
  };

  const handleSearch = () => {
    if (searchKeyword == searchInput && currentPage == 1) {
      getCourses();
      return;
    }
    setSearchKeyword(searchInput);
    setCurrentPage(1);
  };

  const handleRefresh = () => {
    setSearchInput(''); // 无论如何需要清空
    if (searchKeyword == '' && currentPage == 1) {
      /// 如果当前为初始状态，就手动触发一次
      getCourses();
      return;
    }
    setSearchKeyword('');
    setCurrentPage(1);
  };

  const onPageChange = (newPage) => {
    setCurrentPage(newPage);
  };

  const buildCoursesList = () => {
    if (!coursesData) {
      return <Loading />;
    }

    return (
      <div className='flex flex-col flex-grow w-full md:rounded shadow-lg p-5 bg-white min-h-screen'>
        {/* <RouterBackButton onClick={handleBack} /> */}
        <SearchBar
          value={searchInput}
          onChange={handleSearchChange}
          onClickSearch={handleSearch}
          onClickRefresh={handleRefresh}
          placeholder={t('搜索课程')}
        />
        <Spacer height={5} />
        {/* {coursesData == null || coursesData.PageData.length === 0 ? (
          <div className='flex items-center justify-center p-4'>
            <p className='text-gray-400'>暂无数据</p>
          </div>
        ) : (
          
        )} */}
        <DataListWithPagination
          coursesData={coursesData.PageData}
          subsetTab={subsetTab}
          onPageChange={onPageChange}
          getCourses={getCourses}
          currentPage={currentPage}
          totalItems={coursesData.TotalCount}
          itemsPerPage={coursesData.PageSize}
          loading={fetching}
        />
      </div>
    );
  };

  return (
    <main className='flex-grow flex flex-col items-center w-full'>
      {buildCoursesList()}
    </main>
  );
}
