'use client';
import React, { useState, useCallback, useEffect } from 'react';
import TopTabs from '../components/public/TopTabs';
import Pagination from '../components/public/Pagination';
import CoursesList from '../components/courses/CoursesList';
import * as coursesAPI from '../apis/coursesAPI';
import { useSessionStorage } from 'react-use';
import PopularCourses from '../components/courses/PopularCourses';
import PopularCourseAlbums from '../components/courses/PopularCourseAlbums';
import { useParams } from 'react-router-dom';
import FPlatformEnum from '../utils/enum';
import SearchBarWithTwoTab from '../components/public/SearchBarWithTwoTab';

// import * as Select from '@radix-ui/react-select';
// import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from '@radix-ui/react-icons';
export default function CourseHomePage() {
  const { token, platform } = useParams();
  const [kPlatform, setKPlatform] = useSessionStorage(
    'platform',
    platform || FPlatformEnum.web.index,
  );
  const [kToken, setKToken] = useSessionStorage('token', token);
  const [isParamsInit, setIsParamsInit] = useState(false);

  // 在浏览器会话缓存中存页面状态
  const [initTab, setInitTab] = useSessionStorage('currentHomePageTab', '1');
  const [intPage, setIntPage] = useSessionStorage('currentPage', 1);

  /// 当前路由
  const [currentTab, setCurrentTab] = useState(initTab);
  const [coursesData, setCoursesData] = useState(null);
  const [popularCoursesData, setPopularCoursesData] = useState(null);
  const [popularCourseAlbumsData, setPopularCourseAlbumsData] = useState(null);
  const [currentPage, setCurrentPage] = useState(intPage);
  const [tabsList, setTabsListData] = useState([]);
  const [searchInput, setSearchInput] = useState('');
  const [selectedOption, setSelectedOption] = useState('course');

  /// 获取课程数据
  const getCourses = useCallback(async () => {
    // 如果是首页，就不需要传入tab参数，获取【热门专辑】和【热门课程】
    if (currentTab === '1') {
      const coursesData = await coursesAPI.fetchPopularCoursesData();
      const courseAlbumsData = await coursesAPI.fetchPopularCourseAlbumsData();
      // 专辑数据
      const courseAlbumsDataList = !courseAlbumsData.result
        ? []
        : courseAlbumsData.result.PageData;

      // 课程数据
      const coursesDataList = !coursesData.result
        ? []
        : coursesData.result.PageData;
      setPopularCoursesData(coursesDataList);
      setPopularCourseAlbumsData(courseAlbumsDataList);
    } else {
      const data = await coursesAPI.fetchCoursesData(
        currentTab,
        currentPage,
        selectedOption,
        searchInput,
      );
      const coursesDataList = data.result;
      setCoursesData(coursesDataList);
    }
  }, [currentTab, currentPage, selectedOption, searchInput]);

  /// 获取tab数据
  const getCourseLabels = useCallback(async () => {
    const tabsListData = await coursesAPI.getCourseLabelsAsyncData();
    let tabs = [{ name: '首页', code: '1' }];

    for (let i of tabsListData.result) {
      tabs.push({ name: i.Name, code: i.Code });
    }

    setTabsListData(tabs);
  }, []);

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

  useEffect(() => {
    setKToken(token);
    setKPlatform(platform);
    setIsParamsInit(true);
  }, [token, setKToken, setKPlatform, platform]);

  // 根据关键字搜索
  const handleSearch = () => {
    setCurrentPage(1);
    getCourses();
  };

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

  // 当前页码改变时
  const onPageChange = (newPage) => {
    setIntPage(newPage);
    setCurrentPage(newPage);
  };

  // 当前tab改变时
  const handleTabChange = (index) => {
    setInitTab(tabsList[index].code);
    setCurrentTab(tabsList[index].code);
    setCurrentPage(1);
    setSearchInput('');
  };

  // 切换子集tab 专辑或者课程
  const handleChangeSubsetTab = (event) => {
    setSelectedOption(event.target.value);
  };

  return (
    <main className='flex min-h-screen flex-col items-center justify-between p-5 md:p-5'>
      {tabsList.length > 0 && (
        <TopTabs
          tabs={tabsList}
          initTab={currentTab}
          onChangeTab={handleTabChange}></TopTabs>
      )}
      {buildMainContent()}
    </main>
  );

  function buildMainContent() {
    /// 首页的code
    if (currentTab === '1') {
      return buildPopularCoursesList();
    } else {
      return buildCoursesList();
    }
  }

  // 构建课程列表【带分页】
  function buildCoursesList() {
    if (!coursesData) {
      return <div>loading...</div>;
    }

    return (
      <div className='flex-grow flex flex-col items-center w-full'>
        <div className='h-5 md:h-1'></div>
        <div className='flex items-center'>
          <SearchBarWithTwoTab
            selectedOption={selectedOption}
            handleChangeSubsetTab={handleChangeSubsetTab}
            searchInput={searchInput}
            handleSearchChange={handleSearchChange}
            handleSearch={handleSearch}></SearchBarWithTwoTab>
        </div>
        <div className='h-5 md:h-8'></div>
        {coursesData == null || coursesData.PageData.length === 0 ? (
          <div>暂无数据</div>
        ) : (
          <div className='flex flex-col flex-grow w-full'>
            <div className='flex flex-col flex-grow w-full h-full'>
              <div className='flex flex-col flex-grow mb-5 md:px-[5vw]'>
                <CoursesList
                  coursesData={coursesData.PageData}
                  subsetTab={selectedOption}
                  getCourses={getCourses}
                />
              </div>
              <div className='mb-10'></div>
              <Pagination
                totalItems={coursesData.TotalCount}
                itemsPerPage={coursesData.PageSize}
                currentPage={currentPage}
                onPageChange={onPageChange}
              />
            </div>
          </div>
        )}
      </div>
    );
  }

  // 构建热门专辑和热门课程列表
  function buildPopularCoursesList() {
    if (!popularCoursesData) {
      return <div>loading...</div>;
    }
    if (!popularCourseAlbumsData) {
      return <div>loading...</div>;
    }
    return (
      <div className='flex-grow flex flex-col items-center w-full'>
        <div className='flex flex-col flex-grow w-full'>
          <div className='flex flex-col flex-grow w-full h-full'>
            <div className='flex flex-col flex-grow mb-5 md:px-[5vw]'>
              <PopularCourseAlbums
                coursesData={popularCourseAlbumsData}
                subsetTab={'album'}
                getCourses={getCourses}
              />
              <div className='mt-10'></div>
              <PopularCourses
                coursesData={popularCoursesData}
                subsetTab={'course'}
                getCourses={getCourses}
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}
