import React, { memo, useEffect, useRef } from 'react';
import { connect, ConnectedProps } from 'react-redux';
import { useSizeByDomId, useScroll } from 'components/easyUse';
import Loading from 'components/Loading';
import ScreenItem from './ScreenItem';
import {
  getScreens,
  changeInfo,
  deleteScreen,
  copyScreen,
  toNextPage,
  dragScreenStart,
  dragScreenEnd,
  selectScreen,
  unselectScreen,
  clearScreenList,
  Screens,
  ScreensState,
} from 'models/screens';
import styles from './ScreenList.less';
import { GroupState } from 'models/group.types';
import { UserState } from 'models/user.types';
import orderBy from 'lodash/orderBy';
import EasyvNoData from 'components/EasyvNoData';

const CARD_MIN_WIDTH = 280;

interface OwnerProps {
  showAlertBar?: boolean;
}

type IProps = ConnectedProps<typeof connector> & OwnerProps;

function ScreenList({
  screens = [],
  page,
  pageSize,
  selectedScreens,
  loading,
  showAlertBar = false,
  screenCopyable,
  deleteScreen,
  updateScreen,
  copyScreen,
  dragScreenStart,
  dragScreenEnd,
  selectScreen,
  unselectScreen,
  toNextPage,
}: IProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const listRef = useRef<HTMLDivElement>(null);

  const { width: windowWidth, height: windowHeight } = useSizeByDomId();
  const { y } = useScroll(containerRef);

  useEffect(() => {
    if (listRef.current && containerRef.current) {
      const containerHeight = containerRef.current.clientHeight;
      const height = listRef.current.clientHeight;

      if (height - y < containerHeight + CARD_MIN_WIDTH && page * pageSize < screens.length) {
        toNextPage();
      }
    }
  }, [screens, windowWidth, windowHeight, page, y, pageSize, toNextPage]);

  if (!loading && screens.length === 0) {
    return <EasyvNoData />;
  }

  const showedScreens: Screens = screens.slice(0, page * pageSize);
  // .map(d=>{
  //   !d.shareInfo ? d['shareInfo'] = {
  //     title:d.screenName,
  //     description:'',
  //     thumb:d.thumb
  //   }:null;
  //   return d;
  // });

  return (
    <div
      ref={containerRef}
      className={styles.wrap}
      style={{ height: showAlertBar ? 'calc(100vh - 44px - 118px)' : 'calc(100vh - 118px)' }}>
      <div className={styles.container} ref={listRef}>
        {showedScreens.map((item) => {
          return (
            <ScreenItem
              key={item.screenId}
              {...item}
              shareInfo={item.shareInfo}
              isSelected={selectedScreens.includes(item.screenId)}
              deleteScreen={deleteScreen}
              updateScreen={updateScreen}
              copyScreen={copyScreen}
              onDragStart={dragScreenStart}
              onDragEnd={dragScreenEnd}
              onSelected={selectScreen}
              onUnselected={unselectScreen}
              screenCopyable={screenCopyable}
            />
          );
        })}
      </div>

      {loading && <Loading />}
    </div>
  );
}

const mapStateToProps = ({
  screens,
  groups,
  user,
}: {
  screens: ScreensState;
  groups: GroupState;
  user: UserState;
}) => {
  const { search, selectedScreens, loading, page, pageSize, sortType } = screens;
  let { list: screenList } = screens;
  const { current } = groups;
  screenList = screenList.filter((d) => !d.deletedAt);

  let groupScreens: Screens = [];
  if (current === 0) {
    groupScreens = screenList;
  } else if (current === -1) {
    groupScreens = screenList.filter((d) => d.groupId == null);
  } else {
    groupScreens = screenList.filter((d) => d.groupId === current);
  }
  const resultScreens = orderBy(
    groupScreens.filter((d) => d.screenName.toLowerCase().includes(search.toLowerCase())),
    sortType === 'byCreatedAt' ? 'createdAt' : 'updatedAt',
    'desc',
  );
  return {
    screens: resultScreens,
    search,
    selectedScreens,
    loading,
    page,
    pageSize,
    screenCopyable: !(window.appConfig.LOCAL && user.userInfo.type === 'education'),
  };
};

const mapDispatchToProps = {
  getScreens,
  updateScreen: changeInfo,
  copyScreen,
  deleteScreen,
  dragScreenStart,
  dragScreenEnd,
  selectScreen,
  unselectScreen,
  clearScreenList,
  toNextPage,
};

const connector = connect(mapStateToProps, mapDispatchToProps);

export default connector(memo(ScreenList));
