import React, { useState, useCallback, useEffect, useRef } 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 CreateLiveCourseDialog from '../components/courses/CreateLiveCourseDialog';
import Modal from 'react-modal';
import { useCopyToClipboard } from 'react-use';
import { useParams } from 'react-router-dom';
import { 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 SearchBar from '../components/public/SearchBar';
import { useTranslation } from 'react-i18next';
import Loading from '../components/public/Loading';

/// 创建课程模态框
const CreateCourseModal = ({
  isOpen,
  onRequestClose,
  onRequestCloseAndRefresh,
  code,
  readOnly,
}) => {
  const { t, i18n } = useTranslation();
  const [title, setTitle] = useState('');

  const handleCloseModal = () => {
    onRequestClose();
  };

  const handleCloseModalAndRefresh = () => {
    onRequestCloseAndRefresh();
  };
  const formRef = useRef(); // 表单引用

  useEffect(() => {
    if (readOnly) {
      setTitle(t('课程详情'));
    } else {
      if (typeof code === 'string') {
        setTitle(t('编辑课程'));
      } else {
        setTitle(t('创建课程'));
      }
    }
  }, [code, readOnly, t]);

  return (
    <AntdModal
      title={title}
      open={isOpen}
      onCancel={handleCloseModal}
      onOk={handleCloseModal}
      destroyOnClose={true}
      width={850}
      footer={[
        <div className='flex justify-center' key={'course'}>
          <button
            className='rounded border bg-blue-500 hover:bg-blue-400  flex items-center justify-center mx-2 px-4 py-2 w-20'
            onClick={() => {
              if (readOnly) {
                handleCloseModal();
              } else {
                formRef.current.submit();
              }
            }}>
            <span className='text-white font-medium'>{t('确定')}</span>
          </button>
          <button
            className='rounded border bg-white hover:bg-gray-100  flex items-center justify-center mx-2 px-4 py-2 w-20'
            onClick={handleCloseModal}>
            <span className='text-gray-500 font-medium'>{t('取消')}</span>
          </button>
        </div>,
      ]}>
      <div className='flex justify-center mb-4'>
        <CreateLiveCourseDialog
          props={{
            code: code,
            onRequestClose: handleCloseModalAndRefresh,
            readOnly: readOnly,
          }}
          ref={formRef}
        />
      </div>
    </AntdModal>
  );
};

const MyCoursePage = () => {
  const { token, platform, language } = useParams();
  const [initTab, setInitTab] = useSessionStorage(
    'currentMyCourseTab',
    FPlatformEnum.byIndex(platform).isMobile() ? 2 : 1, // 移动端使用我报名的作为默认首页
  );
  const [initPage, setInitPage] = useSessionStorage('currentMyCoursePage', 1);

  const { t, i18n } = useTranslation();
  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(initPage);
  const [currentPageSize, setCurrentPageSize] = useState(10);
  const [currentTab, setCurrentTab] = useState(initTab);
  const [selectedOption, setSelectedOption] = useState('course');
  const [searchInput, setSearchInput] = useState('');
  const [searchKeyword, setSearchKeyword] = useState('');
  const [isShowCourse, setIsShowCourse] = useState(false); // 是否展示课程模态框
  const [editCourseCode, setEditCourseCode] = useState('');
  const [readOnly, setReadOnly] = useState(true);
  const [clipboardState, copyToClipboard] = useCopyToClipboard();
  const [loading, setLoading] = useState(false);

  // 复制当前地址到剪贴板
  const handleCopyUrl = (courseLiveUrl) => {
    if (FPlatformEnum.byIndex(platform).isShell()) {
      coursesAPI.sendCourseEntryNotice(
        `target=copyToClipboard?url=${courseLiveUrl}`,
      );
    }
    copyToClipboard(courseLiveUrl);
    notification.open({
      description: t('分享链接已复制到剪贴板🔗'),
      onClick: () => {
        console.log('Notification Clicked!');
      },
    });
  };

  // 结束课程
  const handleCompletedLiveCourse = async (code) => {
    if (code) {
      const result = await coursesAPI.completedLiveCourseAsync(code);
      if (result.result) {
        getCourses();
      } else {
        message.error(t('结束失败'));
      }
    }
  };
  const navigate = useNavigate();

  const tabsList = [
    { name: t('我创建的'), code: 1 },
    { name: t('我报名的'), code: 2 },
    { name: t('我参与的'), code: 3 },
  ];
  /// 关闭弹窗并刷新
  const handleCloseCreateCourseModalAndRefresh = () => {
    setIsShowCourse(false);
    setEditCourseCode('');
  };

  /// 关闭弹窗不刷新
  const handleCloseCreateCourseModal = () => {
    setIsShowCourse(false);
  };

  // 当前tab改变时
  const handleTabChange = (index) => {
    setInitPage(1);
    setCurrentPage(1);
    setSearchInput('');
    setSearchKeyword('');
    setInitTab(tabsList[index].code);
    setCurrentTab(tabsList[index].code);
    /// 我参与的只有课程
    if (tabsList[index].code === 3) {
      setSelectedOption('course');
    }
  };
  /// 当前路由
  const handleRouterToOtherPage = (path) => {
    navigate(path);
  };

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

  useEffect(() => {
    i18n.changeLanguage(language);
  }, [i18n, language]);

  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) => {
    const newPage = pagination.current;
    setInitPage(newPage);
    setCurrentPage(newPage);
  };
  const onPageMobileChange = (newPage) => {
    // 当前页码改变时
    setInitPage(newPage);
    setCurrentPage(newPage);
    setSearchInput('');
    setSearchKeyword('');
  };

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

  // 根据关键字搜索
  const handleSearch = () => {
    if (searchKeyword === searchInput && currentPage === 1) {
      getCourses();
      return;
    }
    setInitPage(1);
    setCurrentPage(1);
    setSearchKeyword(searchInput);
  };

  const handleRefresh = () => {
    setSearchInput(''); // 无论如何需要清空
    if (searchKeyword === '' && currentPage === 1) {
      getCourses();
      return;
    }
    setInitPage(1);
    setCurrentPage(1);
    setSearchKeyword('');
  };

  const handleCreateCourse = (code) => {
    setReadOnly(false);
    setIsShowCourse(true);
    if (code) {
      setEditCourseCode(code);
    }
  };

  const handleShowCourseDetail = (code) => {
    setReadOnly(true);
    setIsShowCourse(true);
    if (code) {
      setEditCourseCode(code);
    }
  };

  const handleDeleteCourse = async (code) => {
    if (code) {
      const result = await coursesAPI.deleteCourseByCodeAsync({ Code: code });
      if (result.result) {
        getCourses();
      } else {
        message.error(t('删除失败'));
      }
    }
  };
  const handleDeleteAlbum = async (code) => {
    if (code) {
      const result = await coursesAPI.deleteCourseAlbumAsync({
        CourseAlbumCode: code,
      });
      if (result.result) {
        getCourses();
      } else {
        message.error(t('删除失败'));
      }
    }
  };

  // 关键字
  const handleSearchChange = (event) => {
    setSearchInput(event.target.value);
  };

  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'>
        <SearchBar
          value={searchInput}
          onChange={handleSearchChange}
          onClickSearch={handleSearch}
          onClickRefresh={handleRefresh}
          placeholder={t('搜索课程')}></SearchBar>
        {initTab === 1 && !isMobileDevice && (
          <button
            className='bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-1 ml-2 rounded w-20'
            onClick={handleCreateCourse}>
            <span className='text-white font-medium'>
              {t('创建课程【按钮】')}
            </span>
          </button>
        )}
      </div>
      <div className='h-5'></div>
      {!coursesData && <Loading />}
      {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}
                  getCourses={getCourses}
                  platform={platform}
                />
              ) : (
                <CourseTable
                  coursesData={coursesData.PageData}
                  isCourse={selectedOption === 'course'}
                  initTab={initTab}
                  totalSize={coursesData.TotalCount}
                  isPureWeb={isPureWeb}
                  loading={loading}
                  handleTableChange={onPageChange}
                  handlePageSizeChange={onPageSizeChange}
                  handleCreateAlbum={() => {
                    //  屏蔽了创建专辑
                  }}
                  handleCreateCourse={handleCreateCourse}
                  handleDeleteCourse={handleDeleteCourse}
                  handleShowCourseDetail={handleShowCourseDetail}
                  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}
        onRequestCloseAndRefresh={handleCloseCreateCourseModalAndRefresh}
        readOnly={readOnly}></CreateCourseModal>
    </main>
  );
};

export default MyCoursePage;
Modal.setAppElement('#root');
