import React, { useState } 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';

const CourseCard = ({ course, subsetTab, getCourses }) => {
  const navigate = useNavigate();
  const [modalIsOpen, setModalIsOpen] = useState(false);
  const [platform] = useSessionStorage('platform', FPlatformEnum.web.index);

  function openModal() {
    setModalIsOpen(true);
  }

  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);
  };
  const signUpCourseAsync = async (code, name) => {
    let typeIndex = subsetTab === 'album' ? 2 : 1;
    const result = await coursesAPI.signUpCourse(code, typeIndex);
    getCourses();
    if (result) {
      notification.open({
        message: '报名成功：' + name,
        description: '时间：' + 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'>
          {course.NeedPay && !course.IsPay ? (
            <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,
                  );
                }}>
                购买
              </button>
            </div>
          ) : (
            course.SignCourseStatus === 2 && // 未报名
            course.SignCourseStatus !== 5 && // （不）是我创建的
            !course.IsAssistant && // （不）是助教
            !course.IsParticipant && ( // （不）是参会者
              <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);
                  }}>
                  报名
                </button>
              </div>
            )
          )}
          {course.SignCourseStatus === 1 && !course.NeedPay && (
            <div>
              <Tag color='blue' style={{ margin: '0' }}>
                已报名
              </Tag>
            </div>
          )}
          {course.NeedPay && course.IsPay && (
            <div>
              <Tag color='blue' style={{ margin: '0' }}>
                已购买
              </Tag>
            </div>
          )}
        </div>
      </div>
      <PaymentModal
        isOpen={modalIsOpen}
        closeModal={closeModal}
        course={course}
      />
    </div>
  );
};

/// 课程讲师
const CourseLecturers = ({ course }) => {
  if (!course.TeacherName || course.TeacherName.length === 0) {
    return (
      <div className='flex'>
        <p className='text-gray-900 text-sm'>讲师：</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'>讲师：</p>
      <span className='text-sm'>{course.TeacherName}</span>
    </div>
  );
};

export default CourseCard;
