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 * as coursesAPI from '../apis/coursesAPI';
import { useNavigate } from 'react-router-dom';

// 查看更多 -> 全部课程
export default function AllCoursesPage() {
  const subsetTab = 'course';
  const navigate = useNavigate();

  const [coursesData, setCoursesData] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [searchInput, setSearchInput] = useState('');

  const getCourses = useCallback(async () => {
    const data = await coursesAPI.fetchCoursesData(
      '',
      currentPage,
      subsetTab,
      searchInput,
    );
    setCoursesData(data.result);
  }, [currentPage, searchInput]);

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

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

  const handleSearch = () => {
    setCurrentPage(1);
    getCourses();
  };
  const handleBack = () => {
    navigate(-1);
  };

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

  const buildCoursesList = () => {
    if (!coursesData) {
      return <div>loading...</div>;
    }

    return (
      <div className='flex flex-col flex-grow w-full md:rounded shadow-lg p-5 bg-white'>
        <RouterBackButton onClick={handleBack} />
        <SearchBar
          value={searchInput}
          onChange={handleSearchChange}
          onClickSearch={handleSearch}
          placeholder={'搜索课程'}
        />
        <Spacer height={5} />
        {coursesData ? (
          <DataListWithPagination
            coursesData={coursesData.PageData}
            subsetTab={subsetTab}
            onPageChange={onPageChange}
            currentPage={currentPage}
            totalItems={coursesData.TotalCount}
            itemsPerPage={coursesData.PageSize}
          />
        ) : (
          <div>暂无数据</div>
        )}
      </div>
    );
  };

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