import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import DeletedScreenItem from './DeletedScreenItem';
import { restoreScreen, ScreensState, updateScreensSortType } from 'models/screens';
import { selectGroup } from 'models/group';
import styles from './Trash.less';
import { RootState } from 'models';
import EasyvSearchHeader from 'components/EasyvSearchHeader';
import EasyvNoData from 'components/EasyvNoData';

function Trash() {
  const [search, setSearch] = useState('');
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(selectGroup('trash'));
  }, [dispatch]);

  const deletedScreens =
    useSelector((state: RootState) => {
      const { sortType = 'byCreatedAt' } = state.screens as ScreensState;
      return state.screens.list
        .filter((d) => d.deletedAt)
        .sort((a, b) => {
          if (sortType === 'byCreatedAt') return Number(a.createdAt < b.createdAt);
          return Number(a.updatedAt < b.updatedAt);
        })
        .filter((d) => d.screenName.includes(search));
    }) || [];

  const onSelectSortTypeChange = (e) => {
    // 可视化应用更新
    if (e === 'byUpdatedAt') {
      //按修改时间排序
      dispatch(updateScreensSortType('byUpdatedAt'));
      return;
    }
    //按创建时间排序
    dispatch(updateScreensSortType('byCreatedAt'));
  };

  return (
    <div className={styles.container}>
      <div className={styles.tip}>
        <i className="icon iconfont icon-gantanhao" />
        <span>被删除的应用会在回收站保留3天，之后将被彻底删除</span>
      </div>
      <div className={styles.search_wrapper}>
        <EasyvSearchHeader
          currentAllScreenLength={deletedScreens.length}
          filterScreenLength={deletedScreens.length}
          isNoTrashedScreen={false}
          currentGroupName={'回收站'}
          search={search}
          onSelectSortTypeChange={onSelectSortTypeChange}
          style={{ marginBottom: '16px' }}
          onSearchChange={(e) => setSearch(e.target.value)}
        />
      </div>
      {deletedScreens.length > 0 ? (
        <div className={styles.list}>
          {deletedScreens.map((d) => (
            <DeletedScreenItem
              key={d.screenId}
              screenName={d.screenName}
              thumb={d.thumb}
              deletedAt={d.deletedAt}
              expiredAt={d.expiredAt}
              onRestore={() => dispatch(restoreScreen(d.screenId))}
            />
          ))}
        </div>
      ) : (
        <EasyvNoData text="当前回收站为空" />
      )}
    </div>
  );
}

export default Trash;
