'use client';
import React, { useState, useCallback, useEffect, useMemo } from 'react';
import { useCopyToClipboard } from 'react-use';
import { useSessionStorage } from 'react-use';
import FPlatformEnum from '../utils/enum';

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 NomalTabs from '../components/public/NomalTabs';
import PaymentModal from '../components/public/PaymentModal';

import { useParams, useNavigate } from 'react-router-dom';
import { notification, Tag } from 'antd';
import ItemLabels from '../components/public/ItemLabels';

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

  const [platform] = useSessionStorage('platform', FPlatformEnum.web.index);

  // 响应式数据
  const [courseData, setcourseData] = useState(null);
  const [courseCatalogData, setCourseCatalogData] = useState(null);
  // 是否显示报名/购买/取消报名/播放/分享
  const [isShowSignUp, setIsShowSignUp] = useState(false);
  const [isShowBuy, setIsShowBuy] = useState(false);
  const [isShowCancelSignUp, setIsShowCancelSignUp] = useState(false);
  /// TODO 将按钮是否显示的逻辑整合到UI外部
  const [isShowPlay, setIsShowPlay] = useState(false);
  const [isShowShare, setIsShowShare] = useState(false);

  // 来判断是否显示按钮
  useEffect(() => {
    if (courseData) {
      if (
        courseData.Status === 2 && // 已审核
        courseData.SignCourseStatus === 2 && // 未报名
        courseData.SignCourseStatus !== 5 && // （不）是我创建的
        !courseData.NeedPay && // （不）需要购买
        !courseData.IsAssistant && // （不）是助教
        !courseData.IsParticipant // （不）是参会者
      ) {
        setIsShowSignUp(true);
      } else {
        setIsShowSignUp(false);
      }
      if (
        courseData.NeedPay && // 需要购买
        !courseData.isPay // 未购买
      ) {
        setIsShowBuy(true);
      } else {
        setIsShowBuy(false);
      }
      if (
        courseData.SignCourseStatus === 1 && // 已报名
        !courseData.NeedPay // （不）需要购买
      ) {
        setIsShowCancelSignUp(true);
      } else {
        setIsShowCancelSignUp(false);
      }
    }
  }, [courseData]);

  // FIXME: 拆分页面，移除 subsetTab 状态
  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) => {
    setCurrentTab(tabsList[index]);
  };
  // 返回课程列表
  const handleBackToCourseList = () => {
    navigate(-1);
  };

  // 复制当前地址到剪贴板
  const handleCopyUrl = (courseShareUrl) => {
    console.log(
      '%c Line:63 🥪 courseShareUrl',
      'color:#ea7e5c',
      courseShareUrl,
    );
    copyToClipboard(courseShareUrl);
    notification.open({
      description: '分享链接已复制到剪贴板🔗',
      onClick: () => {
        console.log('Notification Clicked!');
      },
    });
  };

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

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

    setCourseCatalogData(courseVideos);
  }, [courseCode, 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();
  };
  const buyCourse = async (code, type) => {
    const buyInfo = await coursesAPI.buyCourse(code, type);

    const { PayUrl } = buyInfo;
    window.open(PayUrl, '_blank');
    // 设置支付二维码内容和显示支付二维码的状态
    // setQRCodeValue(PayUrl); // TODO: 替换为合适的支付二维码内容
    // setIsShowingQRCode(true);
  };

  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() {
    if (currentTab === '简介') {
      return (
        <div className='flex-grow flex flex-col  bg-gray-50 rounded p-5'>
          <div className='text-xl mb-2'>
            {' '}
            {/* FIXME 页面拆分，移除 subsetTab 变量 */}
            {subsetTab === 'album' ? '专辑简介' : '课程简介'}
          </div>
          <div className='text-sm text-gray-600 whitespace-pre-wrap'>
            {/* FIXME 页面拆分，移除 subsetTab 变量 */}
            {subsetTab === 'album'
              ? courseData.Introduction
              : 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.Cover} />
        </div>
        <ItemLabels course={courseData} />
      </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.SignInCount || 0}
        </div>
      </div>
    );
  }

  function onClickPlay() {
    let token = '';
    if (sessionStorage.getItem('token')) {
      token = `/${JSON.parse(sessionStorage.getItem('token'))}`;
    }
    const url =
      '/video_course_player/' + courseData.Code + `/${platform}` + token;
    navigate(url);
  }

  // 报名和分享按钮
  function buildApplyButton() {
    return (
      <div className='flex mt-5 md:mt-0 justify-between md:justify-normal'>
        {isShowSignUp && (
          <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>
        )}
        {isShowBuy && (
          <button
            className='flex-1 md:flex-none bg-blue-500 hover:bg-blue-700 text-white py-2 px-8 rounded mr-5'
            onClick={() => {
              buyCourse(
                courseData.Code,
                FPlatformEnum.byIndex(platform).isMobile() ? 1 : 0,
              );
            }}>
            购买
          </button>
        )}
        {isShowCancelSignUp && (
          <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.NeedPay || courseData.isPay) &&
          (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={onClickPlay}>
              播放
            </button>
          )}
        {subsetTab === 'course' && !courseData.NeedPay && (
          <button
            onClick={() => handleCopyUrl(courseData.CourseShareUrl)}
            className={
              'flex-1 md:flex-none bg-white-300 hover:bg-gray-200 text-black-500 py-2 px-8 rounded border'
            }>
            分享
          </button>
        )}
        <PaymentModal
          isOpen={modalIsOpen}
          closeModal={closeModal}
          course={courseData}
        />
      </div>
    );
  }
}
