"use client";
import React, { useState, useCallback, useEffect, useMemo } from "react";
import { useCopyToClipboard } from "react-use";

import { ArrowLeftIcon } from "@radix-ui/react-icons";
import CourseCoverImage from "../components/courses/CourseCoverImage";
import CoursesCatalog from "../components/courses/CoursesCatalog";
import * as coursesAPI from "../apis/coursesAPI";
import ToastButton from "../components/public/ToastButton";
import NomalTabs from "../components/public/NomalTabs";
import PaymentModal from "../components/public/PaymentModal";

import { useParams, useHistory, useNavigate } from "react-router-dom";
import { notification, Tag } from "antd";

export default function CourseDetailPage() {
  const navigate = useNavigate();
  // 功能钩子
  const [clipboardState, copyToClipboard] = useCopyToClipboard();
  const { courseId, subsetTab } = useParams();
  //   const history = useHistory();

  // 响应式数据
  const [courseData, setcourseData] = useState(null);
  const [courseCatalogData, setCourseCatalogData] = useState(null);
  const [currentTab, setCurrentTab] = useState(
    subsetTab === "course" ? "简介" : "课程列表"
  );
  const [modalIsOpen, setModalIsOpen] = useState(false);

  function openModal() {
    setModalIsOpen(true);
  }

  function closeModal() {
    setModalIsOpen(false);
  }
  // 常量
  const tabsList = ["简介"];
  if (subsetTab === "album") {
    tabsList.unshift("课程列表");
  }

  // 交互事件
  // 切换 Tab
  const handleTabChange = (index) => {
    console.log("Tab 切换至", tabsList[index]);
    setCurrentTab(tabsList[index]);
  };
  // 返回课程列表
  const handleBackToCourseList = () => {
    navigate(-1);
  };
  // 复制当前地址到剪贴板
  const handleCopyUrl = () => {
    copyToClipboard(courseData.CourseLiveUrl);
  };

  // 数据获取：课程数据
  const getCourseDeatil = useCallback(async () => {
    const data = await coursesAPI.fetchCourseDetail(courseId, subsetTab);

    let courseVideos = data?.CourseInfos;
    if (!courseVideos) {
      courseVideos = [];
    }
    setcourseData(data);
    // if (data.CourseType === 1) {
    //   setCourseFileUrl(data.CourseChannel.HttpPullUrl);
    // } else {
    //   setCourseFileUrl(data.DefaultVideoToken);
    // }

    setCourseCatalogData(courseVideos);
  }, [courseId, subsetTab]);
  function prettyDate(date) {
    return new Intl.DateTimeFormat("zh-CN", {
      dateStyle: "full",
      timeStyle: "short",
    }).format(date);
  }

  const signUpCourseAsync = async (code, name) => {
    let typeIndex = subsetTab === "album" ? 2 : 1;
    const result = await coursesAPI.signUpCourse(code, typeIndex);
    await getCourseDeatil();
    if (result) {
      notification.open({
        message: "报名成功：" + name,
        description: "时间：" + prettyDate(new Date()),
        onClick: () => {
          console.log("Notification Clicked!");
        },
      });
    }
  };
  const cancelSignUpCourseAsync = async (code) => {
    await coursesAPI.cancelSignUpCourseAsync(code);
    getCourseDeatil();
  };

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

  // 页面渲染
  if (!courseData) {
    return <div></div>;
  }
  return (
    <main className="flex min-h-screen flex-col items-center justify-between md:p-5">
      <div className="flex flex-col flex-grow w-full md:rounded shadow-lg p-5 bg-white">
        {sessionStorage.getItem("token") && buildRouterBackIcon()}
        <div className="flex flex-col md:flex-row">
          {buildCourseCoverImage()}
          <div className="flex flex-col justify-between flex-grow md:ml-5 mt-2 md:mt-0">
            {buildCourseTitle()}
            {buildApplyButton()}
          </div>
        </div>
        <div className="mt-10 flex flex-col flex-grow">
          {buildTopTabs()}
          {buildContentArea()}
        </div>
      </div>
    </main>
  );

  // 内容主题区域，显示【课程列表】或【简介】
  function buildContentArea() {
    console.log("当前 Tab", currentTab);
    if (currentTab === "简介") {
      return (
        <div className="flex-grow flex flex-col  bg-gray-50 rounded p-5">
          <div className="text-xl mb-2">课程简介</div>
          <div className="text-sm text-gray-600">{courseData.CourseIntro}</div>
        </div>
      );
    }
    return (
      <div className="flex flex-col  bg-gray-50 rounded">
        <CoursesCatalog courseItems={courseCatalogData} />
      </div>
    );
  }

  // 【课程列表】与【简介】Tab
  function buildTopTabs() {
    if (subsetTab === "course") return <div></div>;
    return (
      <NomalTabs
        tabs={tabsList}
        initTab={currentTab}
        onChangeTab={handleTabChange}
      ></NomalTabs>
    );
  }

  // 返回按钮
  function buildRouterBackIcon() {
    return (
      <button
        className="mb-3 w-10 h-10 text-sm rounded border md:border-0 md:hover:border border-gray-400"
        onClick={handleBackToCourseList}
      >
        <center>
          <ArrowLeftIcon className="text-gray-600 w-5 h-5" />
        </center>
      </button>
    );
  }

  // 构建课程封面
  function buildCourseCoverImage() {
    return (
      <div className="pb-[56.25%] md:pb-0 md:w-[320px] h-[180px] cursor-pointer group relative rounded overflow-hidden">
        <div>
          <CourseCoverImage coverImageUrl={courseData.Poster} />
        </div>
        {courseCourseLabels()}
      </div>
    );
  }

  /// 标签
  function courseCourseLabels() {
    if (!courseData.CourseLabels || courseData.CourseLabels.length === 0) {
      return <p></p>;
    }
    let courseLabelsDisplayList = [];
    for (let i of courseData.CourseLabels) {
      courseLabelsDisplayList.push(i.Name);
    }
    const courseLabelsDisplay = courseLabelsDisplayList.join("、");

    if (!courseLabelsDisplay) {
      return null;
    }
    return (
      <div className="hover:bg-blue-50 absolute top-2 left-2 bg-gray-200 opacity-90 text-neutral-800 text-sm px-3 py-1 rounded">
        {courseLabelsDisplay}
      </div>
    );
  }

  // 课程标题
  function buildCourseTitle() {
    return (
      <div>
        <div className="text-3xl mb-2">
          {subsetTab === "course" ? "课程" : "专辑"}：{courseData.Name}
          {subsetTab === "course" && courseData.CourseType === 1 && (
            <div>
              <Tag color="blue">直播</Tag>
            </div>
          )}
        </div>
        <div className="text-l text-gray-500">
          讲师：{courseData.TeacherName} | {courseData.StudentCount || 0} 人学过
        </div>
      </div>
    );
  }

  function openSmallWindow() {
    const screenWidth =
      window.innerWidth ||
      document.documentElement.clientWidth ||
      document.body.clientWidth;
    const screenHeight =
      window.innerHeight ||
      document.documentElement.clientHeight ||
      document.body.clientHeight;
    const width = screenWidth * 0.8;
    const height = screenHeight * 0.8;
    const left = (screenWidth - width) / 2;
    const top = (screenHeight - height) / 2;
    let currentPlatform = "FPlatformEnum.web";

    if (sessionStorage.getItem("currentPlatform") !== undefined) {
      currentPlatform = sessionStorage.getItem("currentPlatform");
    }
    let token = "";
    if (sessionStorage.getItem("token")) {
      token = `/${JSON.parse(sessionStorage.getItem("token"))}`;
    }

    const url =
      "/video_course_player/" + courseData.Code + `/${currentPlatform}` + token;
    const windowFeatures = `width=${width},height=${height},top=${top},left=${left},toolbar=no,menubar=no,location=no,resizable=yes,scrollbars=yes,status=no`;
    console.log("%c Line:249 🥚 url", "color:#3f7cff", url);

    // window.open(url, "_blank", windowFeatures);
    navigate(url);
  }

  // 报名和分享按钮
  function buildApplyButton() {
    return (
      <div className="flex mt-5 md:mt-0 justify-between md:justify-normal">
        {
          // 只有未报名并且不是付费课程的才有报名的按钮
          courseData.SignCourseStatus === 2 && !courseData.NeedPay && courseData.TeacherCode !== sessionStorage.getItem('userCode')  && (
            <button
              className="flex-1 md:flex-none bg-blue-500 hover:bg-blue-700 text-white py-2 px-8 rounded mr-5"
              onClick={() => {
                signUpCourseAsync(courseData.Code, courseData.Name);
              }}
            >
              报名
            </button>
          )
        }
        {
          // 只有未报名并且不是付费课程的才有报名的按钮
          courseData.SignCourseStatus === 2 && courseData.NeedPay && (
            <button
              className="flex-1 md:flex-none bg-blue-500 hover:bg-blue-700 text-white py-2 px-8 rounded mr-5"
              onClick={() => {
                openModal();
              }}
            >
              购买
            </button>
          )
        }
        {courseData.SignCourseStatus === 1 && !courseData.NeedPay && (
          <button
            className="flex-1 md:flex-none bg-blue-500 hover:bg-blue-700 text-white py-2 px-8 rounded mr-5"
            onClick={() => {
              cancelSignUpCourseAsync(courseData.Code);
            }}
          >
            取消报名
          </button>
        )}
        {/* {courseData.NeedPay && courseData.IsPay && (
            <div>
              <Tag color="blue" >
                已购买
              </Tag>
            </div>
          )} */}

        {subsetTab === "course" &&
          (courseData.SignCourseStatus === 1 ||
            !sessionStorage.getItem("token")) && (
            <button
              className="flex-1 md:flex-none bg-blue-500 hover:bg-blue-700 text-white py-2 px-8 rounded mr-5"
              onClick={openSmallWindow}
            >
              播放
            </button>
          )}
        {subsetTab === "course" && (
          <ToastButton
            onClick={handleCopyUrl}
            messageTitle={"分享链接已复制到剪贴板🔗"}
            buttonText={"分享"}
            buttonClassName={
              "flex-1 md:flex-none bg-white-300 hover:bg-gray-200 text-gray-500 py-2 px-8 rounded border"
            }
          />
        )}
        <PaymentModal
          isOpen={modalIsOpen}
          closeModal={closeModal}
          course={courseData}
        />
      </div>
    );
  }
}
