import React, { useContext, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { FaArrowRight } from '@react-icons/all-files/fa/FaArrowRight';
import { translate } from '~helpers/getters';
import styles from './author-description.module.scss';
import Link from '~hooks/link';
import { Context } from '~context/MainProvider';

export default function AuthorDescription({
  author,
  contReadIcon = <FaArrowRight title="Right-pointing Arrow Icon" />,
  template = '',
}) {
  const { translations } = useContext(Context) || {};
  const biographyRef = useRef(null);
  const [isReadMore, setIsReadMore] = useState(true);

  const toggleReadMore = () => {
    biographyRef.current.classList.add(styles.open);
    setIsReadMore(false);
  };

  return (
    <div className={`${styles.description || ''} ${styles[template]}`}>
      <div
        ref={biographyRef}
        className={`${styles.biography} ${
          author?.biography?.split(' ').length > 30 && styles.showReadMore
        }`}
        role="button"
        aria-label="Toggle biography read more"
        tabIndex={0}
        onClick={toggleReadMore}
        onKeyDown={toggleReadMore}
        dangerouslySetInnerHTML={{
          __html:
            author?.biography?.split(' ').length > 30 && isReadMore
              ? `${author?.biography?.split(' ').slice(0, 30).join(' ')} <span class='${
                  styles.contReadText
                }'>...${translate(translations, 'cont_read', 'continue reading')}</span>`
              : author?.biography,
        }}
      />
      {author?.profile_page_path && (
        <Link
          to={author?.profile_page_path}
          title={author?.name}
          className={`${styles.readMore || ''} author-gtm`}
        >
          {translate(translations, 'cont_read', 'continue reading')}
          {contReadIcon}
        </Link>
      )}
    </div>
  );
}

AuthorDescription.propTypes = {
  author: PropTypes.shape({
    name: PropTypes.string,
    biography: PropTypes.string,
    expertise: PropTypes.arrayOf(PropTypes.string),
    profile_page_path: PropTypes.string,
  }).isRequired,
  contReadIcon: PropTypes.node,
  template: PropTypes.string,
};
