import React, { useState, useEffect } from 'react';
// import Image from "next/image";
import { useSessionStorage } from 'react-use';

import CourseCoverImage from './CourseCoverImage';
import PaymentModal from '../public/PaymentModal';
import { useNavigate } from 'react-router-dom';
import * as coursesAPI from '../../apis/coursesAPI';
import { notification, Tag, Tooltip } from 'antd';
import ItemLabels from '../public/ItemLabels';
import FPlatformEnum from '../../utils/enum';
import { useTranslation } from 'react-i18next';

const CourseCard = ({ course, subsetTab, getCourses }) => {
  const navigate = useNavigate();
  const [modalIsOpen, setModalIsOpen] = useState(false);
  const [platform] = useSessionStorage('platform', FPlatformEnum.web.index);
  // 是否显示报名/购买/取消报名/播放/分享
  const [isShowSignUp, setIsShowSignUp] = useState(false);
  const [isShowBuy, setIsShowBuy] = useState(false);
  const { t, i18n } = useTranslation();

  function closeModal() {
    setModalIsOpen(false);
  }
  function prettyDate(date) {
    return new Intl.DateTimeFormat('zh-CN', {
      dateStyle: 'full',
      timeStyle: 'short',
    }).format(date);
  }
  ///TODO 不稳定的路由系统
  const routerToDetailPage = () => {
    navigate('/detail/' + course.Code + '/' + subsetTab);
  };
  // 来判断是否显示按钮
  useEffect(() => {
    if (course) {
      if (
        (course.Status === 2 || course.Status === 4 || subsetTab === 'album') && // 课程状态（已审核 || 已开始）|| 是专辑
        course.SignCourseStatus === 2 && // 未报名
        course.SignCourseStatus !== 5 && // （不）是我创建的
        !course.NeedPay && // （不）需要购买
        !course.IsAssistant && // （不）是助教
        !course.IsParticipant // （不）是参会者
      ) {
        setIsShowSignUp(true);
      } else {
        setIsShowSignUp(false);
      }
      if (
        !course.IsAssistant && // （不）是助教
        !course.IsParticipant && // （不）是参会者
        course.SignCourseStatus !== 5 && // （不）是我创建的
        course.NeedPay && // 需要购买
        !course.isPay // 未购买
      ) {
        setIsShowBuy(true);
      } else {
        setIsShowBuy(false);
      }
    }
  }, [course]);
  const signUpCourseAsync = async (code, name) => {
    let typeIndex = subsetTab === 'album' ? 2 : 1;
    const result = await coursesAPI.signUpCourse(code, typeIndex);
    getCourses();
    if (result) {
      notification.open({
        message: t('报名成功：') + name,
        description: t('时间：') + prettyDate(new Date()),
        onClick: () => {
          console.log('Notification Clicked!');
        },
      });
    }
  };
  const buyCourse = async (code, type) => {
    const buyInfo = await coursesAPI.buyCourse(code, type);

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

  return (
    <div className='flex flex-col rounded shadow-lg p-4 bg-white'>
      <div className='cursor-pointer group relative pb-[56.25%] rounded overflow-hidden'>
        <div onClick={routerToDetailPage}>
          <CourseCoverImage coverImageUrl={course.Cover} />
        </div>
        <ItemLabels course={course} />
      </div>
      <div
        className='group cursor-pointer flex flex-grow items-start justify-between'
        onClick={routerToDetailPage}>
        <h3 className='truncate'>
          <Tooltip
            placement='topLeft'
            title={course.Name}
            className='text-base font-bold mt-1 group-hover:text-blue-500 '>
            {course.Name}
          </Tooltip>
        </h3>

        {course.NeedPay && (
          <div className='text-red-500 text-xl mt-1'>{'￥' + course.Price}</div>
        )}
      </div>

      <div className='mt-1 flex justify-between'>
        <div className='items-start self-start'>
          <CourseLecturers course={course} />
        </div>
        <div className='self-end'>
          {isShowBuy && (
            <div className='self-end'>
              <button
                className='flex-1 md:flex-none bg-blue-500 hover:bg-blue-700 text-white py-2 px-4 rounded'
                onClick={() => {
                  buyCourse(
                    course.Code,
                    FPlatformEnum.byIndex(platform).isMobile() ? 1 : 0,
                  );
                }}>
                {t('购买')}
              </button>
            </div>
          )}
          {isShowSignUp && (
            <div className='self-end'>
              <button
                className='flex-1 md:flex-none bg-blue-500 hover:bg-blue-700 text-white py-2 px-4 rounded'
                onClick={() => {
                  signUpCourseAsync(course.Code, course.Name);
                }}>
                {t('报名')}
              </button>
            </div>
          )}
          {course.SignCourseStatus === 1 && !course.NeedPay && (
            <div>
              <Tag color='blue' style={{ margin: '0' }}>
                {t('已报名')}
              </Tag>
            </div>
          )}
          {course.NeedPay && course.IsPay && (
            <div>
              <Tag color='blue' style={{ margin: '0' }}>
                {t('已购买')}
              </Tag>
            </div>
          )}
        </div>
      </div>
      <PaymentModal
        isOpen={modalIsOpen}
        closeModal={closeModal}
        course={course}
      />
    </div>
  );
};

/// 课程讲师
const CourseLecturers = ({ course }) => {
  const { t, i18n } = useTranslation();

  if (!course.TeacherName || course.TeacherName.length === 0) {
    return (
      <div className='flex'>
        <p className='text-gray-900 text-sm'> {t('讲师：')}</p>
        <span className='text-sm'>{'暂无'}</span>
      </div>
    );
  }

  // const lecturersDisplay = course.TeacherName
  //   .filter((lecturer) => lecturer)
  //   .join("、");

  // if (!lecturersDisplay) {
  //   return null;
  // }

  return (
    <div className='flex'>
      <p className='text-gray-900 text-sm'>{t('讲师：')}</p>
      <span className='text-sm'>{course.TeacherName}</span>
    </div>
  );
};

export default CourseCard;
