'use client';
import { useState, useCallback, useEffect } from 'react';
import TopTabs from '../components/public/TopTabs';
import Pagination from '../components/public/Pagination';
import WechatCoursesList from '../components/courses/WechatCoursesList';
import * as coursesAPI from '../apis/coursesAPI';
import { useSessionStorage } from 'react-use';
import { useParams } from 'react-router-dom';
import { useSearchParams } from 'react-router-dom';
import FPlatformEnum from '../utils/enum';
// import SearchBarWithTwoTab from '../components/public/SearchBarWithTwoTab';
import { useTranslation } from 'react-i18next';
import Loading from '../components/public/Loading';
import { Carousel } from 'antd';

export default function WechatPage() {
  const { t, i18n } = useTranslation();

  const [kPlatform, setKPlatform] = useSessionStorage(
    'platform',
    FPlatformEnum.android.index,
  );
  // const [kToken, setKToken] = useSessionStorage('token', token);
  const [isParamsInit, setIsParamsInit] = useState(false);
  const [searchParams] = useSearchParams();
  console.log(searchParams.get('tid')); // ▶ URLSearchParams {}

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

  /// 当前路由
  const [currentTab, setCurrentTab] = useState(initTabId);
  const [coursesData, setCoursesData] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [tabsList, setTabsListData] = useState([]);
  const [carouselImageList, setCarouselImageList] = useState([]);
  const [searchInput, setSearchInput] = useState('');

  /// 初始化轮播图内容
  const initCarouselImages = useCallback(async () => {
    const data = await coursesAPI.getWXCarouselsAsync(7);
    if (data.result) {
      setCarouselImageList(data.result);
    }
  }, []);

  /// 获取课程数据
  const getCourses = useCallback(async () => {
    // console.log('getCourses', currentTab);
    const data = await coursesAPI.fetchVideoCoursesData(
      currentTab,
      currentPage,
      searchInput,
    );
    const coursesDataList = data.result;
    setCoursesData(coursesDataList);
  }, [currentTab, currentPage, searchInput]);

  /// 获取tab数据
  const getCourseLabels = useCallback(async () => {
    const tabsListData = await coursesAPI.getCourseLabelsAsyncData();
    let tabs = [{ name: t('全部课程'), code: '' }];

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

    setTabsListData(tabs);
    // console.log('tabsListData', tabs);
    // console.log('initTabId', initTabId);
    //  如果当前的 initTabId 存在于 tabsList 中，则设置当前 tab 为 initTabId
    let findTab = false;
    if (tabs.length > 0) {
      const tab = tabs.find((x) => x.code === initTabId);
      if (tab) {
        console.log('set init tab', tab);
        setCurrentTab(tab.code);
        // setInitTab(tab.code);
        findTab = true;
      }
    }
    if (!findTab) {
      console.log('set default tab', tabs[0]);
      setCurrentTab(tabs[0].code);
      // setInitTab(tabs[0].code);
    }
  }, [t, initTabId]);

  useEffect(() => {
    // console.log(initTabId);
    setIsParamsInit(true);
  }, [initTabId]);

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

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

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

  useEffect(() => {
    // 初始化轮播图内容
    initCarouselImages();

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 根据关键字搜索
  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('');
  };

  return (
    <main className='flex min-h-screen flex-col items-center justify-between p-2 pb-10 md:p-5'>
      <div className='h-[20vw] min-h-40 w-full'>
        <Carousel autoplay>
          {carouselImageList.map((item, index) => (
            <div key={index} className='h-[20vw] min-h-40 w-full'>
              <img
                className='w-full h-full object-contain'
                src={item.FileToken}
                alt={item.TransferUrl}
                onClick={
                  // 打开新窗口
                  () => {
                    window.open(item.TransferUrl);
                  }
                }
              />
            </div>
          ))}
        </Carousel>
      </div>

      {tabsList.length > 0 && (
        <TopTabs
          tabs={tabsList}
          initTab={currentTab}
          onChangeTab={handleTabChange}></TopTabs>
      )}
      {buildMainContent()}
    </main>
  );

  function buildMainContent() {
    return buildCoursesList();
  }

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

    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'>
          {/* TODO 用法存在问题，需要根据 AllCoursePage 的用法来修改 */}
          {/* <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>{t('暂无数据')}</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]'>
                <WechatCoursesList
                  coursesData={coursesData.PageData}
                  subsetTab={'course'}
                  getCourses={getCourses}
                />
              </div>
              <div className='mb-10'></div>
              <Pagination
                totalItems={coursesData.TotalCount}
                itemsPerPage={coursesData.PageSize}
                currentPage={currentPage}
                onPageChange={onPageChange}
              />
            </div>
          </div>
        )}
      </div>
    );
  }
}
