import React, { useEffect, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Icon, ICON_SIZE, Typography, TYPOGRAPHY_TYPE } from 'gdb-web-shared-components';
import { bem } from 'utils/bem';
import { ProjectCard, ProjectCardLoader } from 'projects-v2/components';
import { getRecentlyViewedProjects } from 'projects-v2/actions';
import { recentlyViewedProjectsSelector } from 'projects-v2/selectors';
import { Loading } from 'common-v2/types';
import { dateTimeFormatSelector, globalLabelSelector } from 'common/selectors';
import { CARD_SIZE } from './constants';
import { SRecentProjectsContainer, BEM_CLASS } from './s-recent-projects-container';
import { ALL_LABELS_ID } from 'app/components/app-header/constants';

const classes = bem(BEM_CLASS);

export const RecentProjectsContainer = React.memo(() => {
  const dispatch = useDispatch();

  const currentDateTimeFormat = useSelector(dateTimeFormatSelector);
  const { loading, data: projects } = useSelector(recentlyViewedProjectsSelector);
  const globalLabel = useSelector(globalLabelSelector);

  const content = useMemo(() => {
    switch (loading) {
      case Loading.Idle:
      case Loading.Started:
        return (
          <div className={classes('grid')}>
            {[0, 1, 2].map(key => (
              <ProjectCardLoader key={key} isLoading size={CARD_SIZE} />
            ))}
          </div>
        );
      case Loading.Finished:
        return projects.length > 0 ? (
          <div className={classes('grid')} data-selector="recent-projects-container-projects">
            {projects.map(project => (
              <ProjectCard key={project.id} size={CARD_SIZE} dateFormat={currentDateTimeFormat} {...project} />
            ))}
          </div>
        ) : (
          <div className={classes('empty')} data-selector="recent-projects-container-empty">
            <Typography type={TYPOGRAPHY_TYPE.body4}>There are currently no recently viewed projects.</Typography>
          </div>
        );
      case Loading.Failed:
        return (
          <div className={classes('empty')}>
            <Typography type={TYPOGRAPHY_TYPE.body4}>Recent results failed to load. Please reload the page.</Typography>
          </div>
        );
    }
  }, [currentDateTimeFormat, loading, projects]);

  useEffect(() => {
    if (!globalLabel) return;
    dispatch(
      getRecentlyViewedProjects.request({ label: globalLabel.id === ALL_LABELS_ID ? undefined : globalLabel.id })
    );
  }, [dispatch, globalLabel]);

  return (
    <SRecentProjectsContainer>
      <div className={classes('title')}>
        <Icon className={classes('title-icon')} name="history-m" size={ICON_SIZE.medium} />
        <Typography type={TYPOGRAPHY_TYPE.heading2} data-selector="recent-projects-container-title">
          Recently Viewed Projects
        </Typography>
      </div>

      {content}
    </SRecentProjectsContainer>
  );
});
