import React from 'react';
import PropTypes from 'prop-types';
import { StickyContainer } from 'react-sticky';
import Content from './Content';
import Tab from './Tab';
import TabsContainer from './TabsContainer';
import Section from '../Section';

import './tabs.scss';

const { Row } = Section;
const componentName = 'Tabber';

const propTypes = {
  /** @ignore */
  className: PropTypes.string,
  /** @ignore */
  children: PropTypes.node,
  sticky: PropTypes.object,
  scrollSpy: PropTypes.object,
  tabDirection: PropTypes.oneOf(['column', 'row'])
};

const defaultProps = {
  className: undefined,
  children: null,
  sticky: null,
  scrollSpy: null,
  tabDirection: 'column'
};

const Tabs = ({ className, sticky, scrollSpy, children, tabDirection, ...props }) => {
  let TabsComponent;
  const styleName = tabDirection;
  switch (tabDirection) {
    case 'column':
      TabsComponent = Row;
      break;
    case 'row':
    default:
      TabsComponent = 'div';
  }
  const content = (
    <TabsComponent className={className} styleName={styleName} {...props}>
      {React.Children.map(children, child => {
        if (React.isValidElement(child)) {
          const { type } = child;
          switch (true) {
            case type.componentName === 'TabsContainer':
              return React.cloneElement(child, { scrollSpy, sticky, tabDirection });
            case type.componentName === 'TabsContent':
              return React.cloneElement(child, { tabDirection });
            default:
              return child;
          }
        }
        return child;
      })}
    </TabsComponent>
  );
  if (sticky) {
    return (
      <StickyContainer>{content}</StickyContainer>
    );
  }
  return content;
};

Tabs.componentName = componentName;
Tabs.propTypes = propTypes;
Tabs.defaultProps = defaultProps;

Tabs.Tab = Tab;
Tabs.TabsContainer = TabsContainer;
Tabs.Content = Content;

export default Tabs;
