import React, { useState, useCallback, useEffect } from "react";
import TopTabs from "../components/public/TopTabs";
import Pagination from "../components/public/Pagination";
import MyCoursesList from "../components/courses/MyCourseList";
import CourseTable from "../components/courses/CourseTable";
import CreateCourse from "./CreateCoursePage";
import CreateAlbum from "./CreateAlbumPage";
import Modal from "react-modal";
import { useForm } from "antd/lib/form/Form";
import { useCopyToClipboard } from "react-use";
import { useParams } from "react-router-dom";
import { Button, Modal as AntdModal, message, notification } from "antd";
import * as coursesAPI from "../apis/coursesAPI";
import { useSessionStorage } from "react-use";
import { useNavigate } from "react-router-dom";

/// 创建课程模态框
const CreateCourseModal = ({ isOpen, onRequestClose, code, qrCodeValue }) => {
  const [form] = useForm();
  form.resetFields();
  const handleCloseModal = () => {
    onRequestClose();
  };
  useEffect(() => {}, [code]);
  return (
    <AntdModal
      title={typeof code === "string" ? "编辑课程" : "创建课程"}
      open={isOpen}
      onCancel={handleCloseModal}
      onOk={handleCloseModal}
      destroyOnClose={true}
      width={850}
      footer={[
        <div className="flex justify-center">
          <Button
            type="primary"
            size={18}
            onClick={() => {
              form.submit();
            }}
          >
            确定
          </Button>
          <Button size={18} onClick={handleCloseModal}>
            取消
          </Button>
        </div>,
      ]}
    >
      <div className="flex justify-center mb-4">
        <CreateCourse code={code} form={form} onRequestClose={onRequestClose} />
      </div>
    </AntdModal>
  );
};
/// 创建专辑模态框
const CreateAlbumModal = ({ isOpen, onRequestClose, code, qrCodeValue }) => {
  const [form] = useForm();
  form.resetFields();
  const handleCloseModal = () => {
    onRequestClose();
  };
  useEffect(() => {}, [code]);
  return (
    <AntdModal
      title={typeof code === "string" ? "编辑专辑" : "创建专辑"}
      open={isOpen}
      onCancel={handleCloseModal}
      onOk={handleCloseModal}
      destroyOnClose={true}
      width={850}
      footer={[
        <div className="flex justify-center">
          <Button
            type="primary"
            size={18}
            onClick={() => {
              form.submit();
              // handleCloseModal();
            }}
          >
            确定
          </Button>
          <Button size={18} onClick={handleCloseModal}>
            取消
          </Button>
        </div>,
      ]}
    >
      <div className="flex justify-center mb-4">
        <CreateAlbum code={code} form={form} onRequestClose={onRequestClose} />
      </div>
    </AntdModal>
  );
};

const MyCoursePage = () => {
  const [initTab, setInitTab] = useSessionStorage("currentMyCourseTab", 1);
  const [intPage, setIntPage] = useSessionStorage("currentMyCoursePage", 1);

  const { token, currentPlatform } = useParams();
  const [kToken, setKToken] = useSessionStorage("token", token);

  const [isMobileDevice, setIsMobileDevice] = useState(false);
  const [isPureWeb, setIsPureWeb] = useState(false);
  const [coursesData, setCoursesData] = useState(null);
  const [currentPage, setCurrentPage] = useState(intPage);
  const [currentTab, setCurrentTab] = useState(initTab);
  const [selectedOption, setSelectedOption] = useState("course");
  const [isSearch, setSearchButton] = useState(false);
  const [searchInput, setSearchInput] = useState("");
  const [isShowCourse, setIsShowCourse] = useState(false); // 是否展示课程模态框
  const [isShowAlbum, setIsShowAlbum] = useState(false); // 是否展示专辑模态框
  const [editCourseCode, setEditCourse] = useState("");
  const [clipboardState, copyToClipboard] = useCopyToClipboard();

  // 复制当前地址到剪贴板
  const handleCopyUrl = (courseShareUrl) => {
    copyToClipboard(courseShareUrl);
    notification.open({
      // message: "分享成功：" ,
      description: "分享链接已复制到剪贴板🔗",
      onClick: () => {
        console.log("Notification Clicked!");
      },
    });
  };
  // 结束课程
  const handleCompletedLiveCourse = async (code) => {
    if (code) {
      const result = await coursesAPI.completedLiveCourseAsync(code);
      if (result.result) {
        getCourses();
      } else {
        message.error("结束失败");
      }
    }
  };
  const navigate = useNavigate();

  const tabsList = [
    { name: "我创建的", code: 1 },
    { name: "我报名的", code: 2 },
    { name: "我参与的", code: 3 },
  ];
  const handleCloseCreateCourseModal = () => {
    setIsShowCourse(false);
    setEditCourse("");
  };
  const handleCloseAlbumModal = () => {
    setIsShowAlbum(false);
    setEditCourse("");
  };

  // 当前tab改变时
  const handleTabChange = (index) => {
    setSearchInput("");
    setInitTab(tabsList[index].code);
    console.log("Tab 切换至", tabsList[index]);
    setCurrentTab(tabsList[index].code);
  };
  /// 当前路由
  const handleRouterToOtherPage = (path) => {
    navigate(path);
  };

  /// 获取课程数据
  const getCourses = useCallback(async () => {
    const data = await coursesAPI.fetchMyCoursesData(
      currentTab,
      currentPage,
      selectedOption,
      searchInput
    );
    const coursesDataList = data.result;
    setCoursesData(coursesDataList);
    // console.log("%c Line:228 🍆 navigator.userAgent", "color:#ffdd4d", navigator.userAgent);
    // console.log("%c Line:167 🍪 navigator", "color:#93c0a4", navigator);
  }, [currentTab, currentPage, searchInput, selectedOption]);

  useEffect(() => {
    getCourses();
  }, [getCourses, editCourseCode]);
  useEffect(() => {
    if (
      currentPlatform === "FPlatformEnum.webOnWin" ||
      currentPlatform === "FPlatformEnum.webOnMac"
    ) {
      setIsPureWeb(false);
    } else if (currentPlatform === "FPlatformEnum.web") {
      setIsPureWeb(true);
    } else {
      setIsMobileDevice(true);
    }
  }, [currentPlatform]);

  const onPageChange = (pagination, filters) => {
    console.log("Page 切换至", pagination.current);
    const newPage = pagination.current;
    setIntPage(newPage);
    setCurrentPage(newPage);
  };
  const onPageMobileChange = (newPage) => {
    // 当前页码改变时
    setIntPage(newPage);
    setCurrentPage(newPage);
    setSearchInput("");
  };

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

  // 根据关键字搜索
  const handleSearch = () => {
    setSearchButton(!isSearch);
  };

  const handleCreateCourse = (code) => {
    setIsShowCourse(true);
    if (code) {
      setEditCourse(code);
    }
  };

  const handleCreateAlbum = (code) => {
    setIsShowAlbum(true);
    if (code) {
      setEditCourse(code);
    }
  };
  const handleDeleteCourse = async (code) => {
    if (code) {
      const result = await coursesAPI.deleteCourseByCodeAsync({ Code: code });
      if (result.result) {
        getCourses();
      } else {
        message.error("删除失败");
      }
    }
  };
  const handleDeleteAlbum = async (code) => {
    if (code) {
      const result = await coursesAPI.deleteCourseAlbumAsync({
        CourseAlbumCode: code,
      });
      if (result.result) {
        getCourses();
      } else {
        message.error("删除失败");
      }
    }
  };

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

  return (
    <main className="flex min-h-screen flex-col p-5 md:p-5">
      <TopTabs
        tabs={tabsList}
        initTab={currentTab}
        onChangeTab={handleTabChange}
      ></TopTabs>

      <div className="flex items-center">
        <div className="search-bar bg-blue-500 hover:bg-blue-600 rounded-lg overflow-hidden shadow-md 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>
        {initTab === 1 && selectedOption === "course" && !isMobileDevice && (
          <button
            className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-3 mx-6 rounded"
            onClick={handleCreateCourse}
          >
            <span className="text-white font-medium">创建课程</span>
          </button>
        )}
        {initTab === 1 && selectedOption === "album" && !isMobileDevice && (
          <button
            className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-3 mx-6 rounded"
            onClick={handleCreateAlbum}
          >
            <span className="text-white font-medium">创建专辑</span>
          </button>
        )}
      </div>
      <div className="h-5"></div>
      {!coursesData && <div>Loading...</div>}
      {coursesData && (
        <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 mb-5">
              {isMobileDevice ? (
                <MyCoursesList
                  coursesData={coursesData.PageData}
                  subsetTab={selectedOption}
                  currentTab={currentTab}
                  currentPlatform={currentPlatform}
                />
              ) : (
                <CourseTable
                  coursesData={coursesData.PageData}
                  isCourse={selectedOption === "course"}
                  initTab={initTab}
                  totalSize={coursesData.TotalCount}
                  isPureWeb={isPureWeb}
                  handleTableChange={onPageChange}
                  handleCreateAlbum={handleCreateAlbum}
                  handleCreateCourse={handleCreateCourse}
                  handleDeleteCourse={handleDeleteCourse}
                  handleDeleteAlbum={handleDeleteAlbum}
                  handleCopyUrl={handleCopyUrl}
                  handleRouterToOtherPage={handleRouterToOtherPage}
                  handleCompletedLiveCourse={handleCompletedLiveCourse}
                  currentPage={currentPage}
                  currentPlatform={currentPlatform}
                ></CourseTable>
              )}
            </div>
            <div className="mb-10"></div>
            {isMobileDevice && (
              <Pagination
                totalItems={coursesData.TotalCount}
                itemsPerPage={coursesData.PageSize}
                currentPage={currentPage}
                onPageChange={onPageMobileChange}
              />
            )}
          </div>
        </div>
      )}
      <CreateCourseModal
        isOpen={isShowCourse}
        code={editCourseCode}
        onRequestClose={handleCloseCreateCourseModal}
      ></CreateCourseModal>
      <CreateAlbumModal
        isOpen={isShowAlbum}
        code={editCourseCode}
        onRequestClose={handleCloseAlbumModal}
      ></CreateAlbumModal>
    </main>
  );
};

export default MyCoursePage;
Modal.setAppElement("#root");
