import React, { useState, MouseEvent, useRef, useEffect } from 'react';
import cx from 'classnames';
import ReactGA from 'react-ga';
import { MarketComment } from '../store/markets.types';

interface Props {
  comment: MarketComment;
}

const ShowMore = ( { comment }: Props) => {
  const [ isExpanded, setIsExpanded ] = useState(false);
  const [ isTextTruncatable, setIsTextTruncatable ] = useState(false);
  const paragraphRef = useRef<HTMLParagraphElement>(null);

  useEffect(() => {
    if (paragraphRef?.current) {
      setIsTextTruncatable(paragraphRef.current.scrollHeight > paragraphRef.current.clientHeight);
    }
  }, [ paragraphRef ]);

  const toggle = (e: MouseEvent) => {
    e.preventDefault();
    if (!isExpanded) {
      ReactGA.event({
        category: 'OnPage function',
        action: 'ReadFullComment',
        label: comment.id.toString(),
      });
    }
    setIsExpanded(!isExpanded);
  };

  const toggleText = isExpanded ? 'Collapse' : 'Read full comment' ;
  const toggleIcon = isExpanded ? 'icon-flat-arrow-up' : 'icon-flat-arrow-down';

  return (
    <>
      <div className="u-margin-bottom">
        <p ref={paragraphRef}
          className={cx('c-show-more__text o-text__paragraph o-text__paragraph--small ', { 'c-show-more__text--expanded': isExpanded })}>
          {comment.comment}
        </p>
      </div>
      { isTextTruncatable &&
        <a href="#" className="o-text__link u-margin--none" onClick={toggle}>
          { toggleText } 
          <i className={cx('o-gutter-left--small c-show-more__icon', toggleIcon)} />
        </a>
      }
    </>
  );
};

export { ShowMore };
