import React, { useState, useEffect } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

import returnDefaultCenter from 'store/utils/projectHelpers';

// Import actions here

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import WorkspaceCard from 'components/listItems/WorkspaceCard';
import actionsBuilder from 'store/appActions';
import MapStructure from 'components/structure/MapStructure';
import qs from 'query-string';
import map from 'lodash/map';
import styleIdentifiers from './favoriteWorkspaces.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type FavoriteWorkspacesProps = StateProps & DispatchProps & OwnProps;

const LIMIT = 50;

const FavoriteWorkspaces = (props: FavoriteWorkspacesProps) => {
  const {
    location: { search },
  } = props;
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);

  const workspaces = useSelector((state: StoreState) => state.workspace.list);

  const profile = useSelector(
    (state: StoreState) => state.account.profile && state.account.profile.data,
  );
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const { workspaceList, workspaceListReset } = actionsBuilder(dispatch, ['list', 'list.reset']);

  const searchParams = qs.parse(search);

  useEffect(() => {
    if (profile.getFavorites) {
      const array = map(profile.getFavorites, fav => {
        return fav.ressourceId;
      });

      console.log('array', array);
      workspaceList({
        data: {
          _ids: array,
          pagination: {
            limit: LIMIT,
            skip: ((searchParams?.page || 1) - 1) * LIMIT,
          },
        },
      });
    }
  }, [search]);

  return (
    <>
      {workspaces && workspaces.loaded && (
        <MapStructure
          list={workspaces}
          className={styles('favorite-workspaces')}
          center={returnDefaultCenter(workspaces.data)}
          count={workspaces?.count}
          limit={LIMIT}
          currentPage={searchParams.page}
        >
          <h1 className={styles('title')}>
            <TextItem path="pages.home.favorite" />
          </h1>
          <div className={styles('card-wrapper')}>
            {workspaces &&
              workspaces.data &&
              workspaces.data.map((item, index) => {
                return <WorkspaceCard key={index} view="home" item={item} />;
              })}
            {workspaces && workspaces.loaded && workspaces.data && !workspaces.data.length && (
              <div className={styles('no-results')}>
                <TextItem path="pages.home.notFoundFavorite" />
              </div>
            )}
          </div>
        </MapStructure>
      )}
    </>
  );
};

export default FavoriteWorkspaces;
