import React from 'react';
import * as Text from 'app/shared/components/text/text';
import { Spinner } from 'app/shared/components/spinner/spinner';
import { useDispatch, useSelector } from 'react-redux';
import { createMarketsIsLoadingSelector, selectIsMoreComments, selectOrderedComments } from '../store/markets.selectors';
import { MARKETS } from '../store/markets.constants';
import { increaseMarketsCommentariesLimit } from '../store/markets.actions';
import { ShowMore } from './showMore';
import datePipe from 'app/shared/pipes/date.pipe';

const MarketComments = () => {
  const dispatch = useDispatch();
  const comments = useSelector(selectOrderedComments);
  const isMore = useSelector(selectIsMoreComments);
  const isLoading = useSelector(createMarketsIsLoadingSelector([ MARKETS.FETCH_COMMENTARIES_SELECTOR ]));

  return (
    <div className="c-market-comments">
      <div className="c-market-comments__headline">
        <Text.Headline size="h2">Market comments</Text.Headline>
      </div>
      <div className="c-market-comments__container">
        { isLoading ? <Spinner /> :
          comments.map((item) => (
            <div className="c-market-comments__comment" key={`comment-${item.id}`}>
              <Text.Label extraClass="u-margin-bottom--small">
                {`${datePipe.formatLongNotUS(item.relevantDate)} - WEEK ${datePipe.getWeekNumber(item.relevantDate)}`}
              </Text.Label>
              <div className="c-market-comments__read-more">
                <ShowMore comment={item} />
              </div>
            </div>
          ))
        }
        <div className="u-display--flex u-justify-content-center u-margin-top--big">
          { !isLoading && isMore &&
          <button className="o-button__primary" onClick={() => dispatch(increaseMarketsCommentariesLimit())}>
            Load more
          </button>
          }
        </div>
      </div>
    </div>
  );
};

export { MarketComments };
