import React, { useContext, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { translate } from '~helpers/getters';
import styles from './author-description.module.scss';
import { Context } from '~context/MainProvider';

export default function AuthorDescription({
  author,
  template = '',
  readMore = false,
  maximumLength = 30,
}) {
  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 > maximumLength && readMore
            ? styles.showReadMore
            : ''
        }`}
        role="button"
        aria-label="Toggle biography read more"
        tabIndex={0}
        onClick={toggleReadMore}
        onKeyDown={toggleReadMore}
        dangerouslySetInnerHTML={{
          __html:
            author?.biography?.split(' ').length > maximumLength && isReadMore
              ? `${author?.biography?.split(' ').slice(0, maximumLength).join(' ')} <span class='${
                  styles.contReadText
                }'>${translate(translations, 'toggle_read', '...continue reading')}</span>`
              : author?.biography,
        }}
      />
    </div>
  );
}

AuthorDescription.propTypes = {
  author: PropTypes.shape({
    name: PropTypes.string,
    biography: PropTypes.string,
    expertise: PropTypes.arrayOf(PropTypes.string),
    profile_page_path: PropTypes.string,
  }).isRequired,
  template: PropTypes.string,
  readMore: PropTypes.bool,
  maximumLength: PropTypes.number,
};
