import React, { useState, useRef, useEffect } from 'react';
import PropTypes from 'prop-types';

import styles from './collapse.module.scss';

const Collapse = ({
  buttonText,
  contentText,
  onlyMobile = false,
  onlyDesktop = false,
  initOpen = false,
  maxHeight = 0,
}) => {
  const [maxHeightStyle, setMaxHeightStyle] = useState(maxHeight);
  const contentRef = useRef(React.createRef());

  useEffect(() => {
    if (initOpen) {
      setMaxHeightStyle(contentRef.current.scrollHeight);
    }
  }, [initOpen]);

  const clickHandler = () => {
    if (maxHeightStyle === 0) {
      setMaxHeightStyle(contentRef.current.scrollHeight);
    } else {
      setMaxHeightStyle(0);
    }
  };

  return (
    <div className={styles?.collapseContainer || ''}>
      <div className={maxHeightStyle !== 0 ? styles?.active || '' : ''}>
        <button
          type="button"
          onClick={clickHandler}
          className={`${onlyMobile ? styles?.buttonM || '' : ''} ${
            onlyDesktop ? styles?.buttonD || '' : ''
          } ${styles?.button || ''} ${
            maxHeightStyle !== 0 ? styles?.invertArrow || '' : ''
          } collapse-gtm btn-cta`}
        >
          {buttonText}
        </button>
        <div
          ref={contentRef}
          className={`${onlyMobile ? styles?.contentM || '' : ''} ${
            onlyDesktop ? styles?.contentD || '' : ''
          } ${styles?.content || ''}`}
          style={onlyMobile || onlyDesktop ? { maxHeight: maxHeightStyle } : {}}
        >
          {contentText}
        </div>
      </div>
    </div>
  );
};

Collapse.propTypes = {
  buttonText: PropTypes.string,
  contentText: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
  onlyMobile: PropTypes.bool,
  onlyDesktop: PropTypes.bool,
  initOpen: PropTypes.bool,
  maxHeight: PropTypes.number,
};

export default Collapse;
