/* eslint-disable no-nested-ternary */
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames/bind';
import styles from './typography.scss';
import Text from './text';

const Paragraph = ({
  children,
  underline,
  mark,
  ellipses,
  bold,
  inverse,
  small,
}) => {
  const cx = classnames.bind(styles);

  const [visible, setVisible] = useState(false);

  const truncateString = (string, length) => {
    let useLength = 24;

    if (typeof length !== 'boolean') {
      useLength = length;
    }

    // Increase length amount
    useLength *= 5;

    let trimmed = string.substr(0, useLength);

    // Trim if middle of a word
    trimmed = trimmed.substr(
      0,
      Math.min(trimmed.length, trimmed.lastIndexOf(' '))
    );

    return trimmed;
  };

  return (
    <p
      className={cx('typography', 'typography_paragraph', {
        typography__underline: underline,
        typography__mark: mark,
        typography__bold: bold,
        typography__inverse: inverse,
        typography__small: small,
      })}
    >
      {ellipses
        ? visible
          ? children
          : truncateString(children, ellipses)
        : children}
      {ellipses && (
        <span className={cx('typography_paragraph__ellipses')}>
          <Text onClick={() => setVisible(!visible)}>...</Text>
        </span>
      )}
    </p>
  );
};

Paragraph.defaultProps = {
  ellipses: false,
  mark: false,
  small: false,
  underline: false,
  inverse: false,
  bold: false,
};

Paragraph.propTypes = {
  bold: PropTypes.bool,
  children: PropTypes.node.isRequired,
  ellipses: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
  mark: PropTypes.bool,
  small: PropTypes.bool,
  underline: PropTypes.bool,
  inverse: PropTypes.bool,
};

export default Paragraph;
