import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import jump from 'jump.js';
import omit from 'lodash/omit';

import Button from '../../Button';

const propTypes = {
  onClick: PropTypes.func,
  duration: PropTypes.number,
  offset: PropTypes.number,
  to: PropTypes.string,
  withHashTag: PropTypes.bool,
  scrollJump: PropTypes.bool,
  variant: PropTypes.string
};

const defaultProps = {
  onClick: undefined,
  duration: 500,
  offset: 0,
  to: '',
  withHashTag: false,
  scrollJump: null,
  variant: 'button-collapsible-card'
};

class CollapsibleItem extends PureComponent {
  componentDidMount = () => {
    const { scrollJump, offset, to } = this.props;
    if (scrollJump && `#${to}` === window.location.hash) {
      jump(`#${to}`, { duration: 0, offset });
    }
  };

  handleClick = e => {
    const { onClick, scrollJump, duration, to, offset, withHashTag } = this.props;
    if (typeof onClick === 'function') onClick(e);
    if (scrollJump) {
      if (withHashTag) {
        const { scrollX, scrollY } = window;
        window.location.hash = to;
        window.scroll(scrollX, scrollY);
        setTimeout(() => {
          jump(`#${to}`, { duration, offset });
        }, 50);
      } else {
        jump(`#${to}`, { duration, offset });
      }
    }
    e.preventDefault();
  };

  render() {
    const { variant } = this.props;
    return (
      <Button
        onClick={this.handleClick}
        variant={variant}
        {...omit(this.props, Object.keys(propTypes))}
      />
    );
  }
}


CollapsibleItem.propTypes = propTypes;
CollapsibleItem.defaultProps = defaultProps;


export default CollapsibleItem;
