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';
import FPlatformEnum from '../utils/enum';
import SearchBarWithTwoTab from '../components/public/SearchBarWithTwoTab';

/// 创建课程模态框
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, platform } = useParams();

  const [kPlatform, setKPlatform] = useSessionStorage(
    'platform',
    platform || FPlatformEnum.web.index,
  );
  const [kToken, setKToken] = useSessionStorage('token', token);
  const [isParamsInit, setIsParamsInit] = useState(false);

  const [isMobileDevice, setIsMobileDevice] = useState(false);
  const [isPureWeb, setIsPureWeb] = useState(false);
  const [coursesData, setCoursesData] = useState(null);
  const [currentPage, setCurrentPage] = useState(intPage);
  const [currentPageSize, setCurrentPageSize] = useState(10);
  const [currentTab, setCurrentTab] = useState(initTab);
  const [selectedOption, setSelectedOption] = useState('course');
  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({
      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) => {
    setCurrentPage(1);
    setSearchInput('');
    setInitTab(tabsList[index].code);
    setCurrentTab(tabsList[index].code);
  };
  /// 当前路由
  const handleRouterToOtherPage = (path) => {
    navigate(path);
  };

  /// 获取课程数据
  const getCourses = useCallback(async () => {
    const data = await coursesAPI.fetchMyCoursesData(
      currentTab,
      currentPage,
      currentPageSize,
      selectedOption,
      searchInput,
    );
    const coursesDataList = data.result;
    setCoursesData(coursesDataList);
  }, [currentTab, currentPage, currentPageSize, searchInput, selectedOption]);

  useEffect(() => {
    if (isParamsInit) {
      getCourses();
    }
  }, [getCourses, editCourseCode, isParamsInit]);

  useEffect(() => {
    setIsPureWeb(FPlatformEnum.byIndex(platform).isPureWeb());
    setIsMobileDevice(FPlatformEnum.byIndex(platform).isMobile());
  }, [platform]);

  useEffect(() => {
    setKToken(token);
    setKPlatform(platform);
    setIsParamsInit(true);
  }, [token, setKToken, setKPlatform, platform]);

  const onPageChange = (pagination, filters) => {
    const newPage = pagination.current;
    setIntPage(newPage);
    setCurrentPage(newPage);
  };
  const onPageMobileChange = (newPage) => {
    // 当前页码改变时
    setIntPage(newPage);
    setCurrentPage(newPage);
    setSearchInput('');
  };

  const onPageSizeChange = (current, size) => {
    setCurrentPageSize(size);
  };

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

  // 根据关键字搜索
  const handleSearch = () => {
    setCurrentPage(1);
    getCourses();
  };

  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);
    setCurrentPage(1);
  };

  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'>
        <SearchBarWithTwoTab
          selectedOption={selectedOption}
          handleChangeSubsetTab={handleChangeSubsetTab}
          searchInput={searchInput}
          handleSearchChange={handleSearchChange}
          handleSearch={handleSearch}></SearchBarWithTwoTab>
        {initTab === 1 && selectedOption === 'course' && !isMobileDevice && (
          <button
            className='h-9 bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-1 ml-2 rounded w-20'
            onClick={handleCreateCourse}>
            <span className='text-white font-medium'>创建课程</span>
          </button>
        )}
        {initTab === 1 && selectedOption === 'album' && !isMobileDevice && (
          <button
            className='h-9 bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-1 ml-2 rounded w-20'
            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}
                  platform={platform}
                />
              ) : (
                <CourseTable
                  coursesData={coursesData.PageData}
                  isCourse={selectedOption === 'course'}
                  initTab={initTab}
                  totalSize={coursesData.TotalCount}
                  isPureWeb={isPureWeb}
                  handleTableChange={onPageChange}
                  handlePageSizeChange={onPageSizeChange}
                  handleCreateAlbum={handleCreateAlbum}
                  handleCreateCourse={handleCreateCourse}
                  handleDeleteCourse={handleDeleteCourse}
                  handleDeleteAlbum={handleDeleteAlbum}
                  handleCopyUrl={handleCopyUrl}
                  handleRouterToOtherPage={handleRouterToOtherPage}
                  handleCompletedLiveCourse={handleCompletedLiveCourse}
                  currentPage={currentPage}
                  currentPageSize={currentPageSize}
                  platform={platform}></CourseTable>
              )}
            </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');
