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 = {
  index: PropTypes.number,
  onChange: PropTypes.func,
  onClick: PropTypes.func,
  component: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.object,
    PropTypes.func
  ]),
  tabDirection: PropTypes.string,
  duration: PropTypes.number,
  offset: PropTypes.number,
  to: PropTypes.string,
  withHashTag: PropTypes.bool,
  scrollSpy: PropTypes.object
};

const defaultProps = {
  index: 0,
  onChange: null,
  onClick: null,
  component: 'button',
  scrollSpy: null,
  tabDirection: 'column',
  duration: 0,
  offset: 0,
  to: '',
  withHashTag: false,
  children: null
};

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

  handleClick = e => {
    const { index, onChange, onClick, scrollSpy, duration, to, offset, withHashTag } = this.props;
    if (typeof onChange === 'function') onChange(index);
    if (typeof onClick === 'function') onClick(e);
    if (scrollSpy) {
      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 { tabDirection, ...rest } = this.props;
    return (
      <Button
        variant={tabDirection === 'column' ? 'tab' : 'dash-night-blue'}
        size={tabDirection === 'column' ? 'md' : 'nav-bar-level-2'}
        onClick={this.handleClick}
        {...omit(rest, Object.keys(propTypes))}
      />
    );
  }
}


Tab.componentName = 'Tab';

Tab.propTypes = propTypes;
Tab.defaultProps = defaultProps;


export default Tab;
