import React from 'react';
import { bool, string, func, node, arrayOf, shape } from 'prop-types';
import styled from 'styled-components';
import classnames from 'classnames';
import { REM_UNIT_LG, COLOR_PRIMARY, GRAY_X11, SONIC_SILVER } from '@vincent_za/styles';
import scrollHOC from '../Scroll/component';

export const CN_TABS_TITLES = 'tabs-titles';
export const CN_TABS_TITLE = 'tabs-title';
export const CN_TABS_CONTENT = 'tabs-content';

const Wrap = styled.div``;

const Titles = styled.ul`
  display: flex;
  margin: 0 ${REM_UNIT_LG};
  text-transform: uppercase;
`;

const Title = styled.li`
  margin-right: ${REM_UNIT_LG};
  padding-bottom: ${REM_UNIT_LG};
  box-shadow: ${props => props.isActive && `inset 0 -2px ${COLOR_PRIMARY}`};
  color: ${props => props.isActive ? GRAY_X11 : SONIC_SILVER};
  cursor: pointer;

  &:hover {
    color: ${GRAY_X11};
  };
`;

const Detail = styled.div``;

const DetailScroll = scrollHOC(Detail);

class Tabs extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeTab: this.props.titles[0],
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (nextState.activeTab !== this.state.activeTab) return true;
    if (nextProps.children !== this.props.children) return true;
    return false;
  }

  onTabSelect = (selectedTab) => {
    this.setState({ activeTab: selectedTab });
    this.props.callback({ selectedTab });
  }

  render() {
    const { activeTab } = this.state;
    const { isTouchDevice, titles, children, className } = this.props;

    return (
      <Wrap className={className}>
        <Titles className={CN_TABS_TITLES}>
          {
            titles.map(title => (
              <Title
                isActive={activeTab === title}
                onClick={() => this.onTabSelect(title)}
                className={classnames(CN_TABS_TITLE, { 'is-active': activeTab === title })}
                key={title}
              >
                {title}
              </Title>
            ))
          }
        </Titles>
        <DetailScroll isTouchDevice={isTouchDevice} isNoOverflow isOverflowY className={CN_TABS_CONTENT}>
          {children[activeTab]}
        </DetailScroll>
      </Wrap>
    );
  }
}

Tabs.propTypes = {
  isTouchDevice: bool.isRequired,
  titles: arrayOf(string).isRequired,
  children: shape(node.isRequired).isRequired,
  className: string,
  callback: func,
};

Tabs.defaultProps = {
  className: undefined,
  callback() {},
};

export default Tabs;
