"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, useNavigate } from "react-router-dom";
import { ConfigProvider, DatePicker, message } from "antd";
import zhCN from "antd/locale/zh_CN";

// import * as Select from '@radix-ui/react-select';
// import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from '@radix-ui/react-icons';
export default function CourseHomePage() {
  const { token, currentPlatform } = useParams();
  console.log(
    "%c Line:18 🍒 currentPlatform",
    "color:#4fff4B",
    currentPlatform
  );
  useSessionStorage("token", token);
  console.log("%c Line:19 🍫 token", "color:#4fff4B", token);
  if (currentPlatform !== undefined) {
    sessionStorage.setItem("currentPlatform", currentPlatform);
  } else {
    sessionStorage.setItem("currentPlatform", "FPlatformEnum.web");
  }

  // 在浏览器会话缓存中存页面状态
  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 [isSearch, setSearchButton] = useState(false);
  const navigate = useNavigate();

  // const tabsList = ["首页", "产筛", "急诊重症", "学术", "学术峰会", "麻醉", "规培", "质控"];

  /// 获取课程数据
  const getCourses = useCallback(async () => {
    console.log("%c Line:95 🍤 window", "color:#ed9ec7", window);

    // 如果是首页，就不需要传入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, isSearch]);

  /// 获取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);
    setCurrentPage(1);
  }, []);

  useEffect(() => {
    getCourseLabels();
    getCourses();
  }, [getCourseLabels, getCourses]);
  // 根据关键字搜索
  const handleSearch = () => {
    setSearchButton(!isSearch);
  };
  // 关键字
  const handleSearchChange = (event) => {
    setSearchInput(event.target.value);
  };

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

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

  // 切换子集tab 专辑或者课程
  const handleChangeSubsetTab = (event) => {
    setSelectedOption(event.target.value);
  };
  /// 跳转到更多页面
  const routerToMore = (type) => {
    navigate("/course_or_album_more/" + type);
  };
  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-5 md:p-5">
      <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">
          <div className="search-bar bg-blue-500 hover:bg-blue-600 rounded-lg overflow-hidden shadow  flex items-center">
            <div className=" bg-white rounded-l-lg flex items-center ">
              <select
                id="my-select"
                className="search-bar-select bg-white  rounded-l-lg px-3 py-2 focus:outline-none"
                value={selectedOption}
                onChange={handleChangeSubsetTab}
              >
                <option value="course">课程</option>
                <option value="album">专辑</option>
              </select>
              <input
                type="text"
                placeholder={
                  selectedOption === "course" ? "搜索课程" : "搜索专辑"
                }
                value={searchInput}
                onChange={handleSearchChange}
                className=" px-2 py-1 mr-2 flex-grow md:min-w-[300px] md:flex-grow-0 bg-transparent  focus:outline-none w-full border-l border-l-[width]"
              />
            </div>

            <button
              className="search-bar-button border-none outline-none flex items-center justify-center px-4 w-20"
              onClick={handleSearch}
            >
              <span className="text-white font-medium">搜索</span>
            </button>
          </div>
        </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}
                routerToMore={routerToMore}
              />
              <div className="mt-10"></div>
              <PopularCourses
                coursesData={popularCoursesData}
                subsetTab={"course"}
                getCourses={getCourses}
                routerToMore={routerToMore}
              />
            </div>
          </div>
        </div>
      </div>
    );
  }
}
