import React, { PureComponent, Children, isValidElement } from 'react';
import PropTypes from 'prop-types';
import Steps from './Steps';
import Step from './Step';
import StepperContent from './StepperContent';

import './stepper.scss';

class Stepper extends PureComponent {
  static propTypes = {
    /** @ignore */
    className: PropTypes.string,
    /** @ignore */
    children: PropTypes.node,
    variant: PropTypes.string,
    withBorder: PropTypes.bool,
    withRightArrow: PropTypes.bool,
    size: PropTypes.oneOf(['sm', 'md', 'lg'])
  };

  static defaultProps = {
    className: undefined,
    children: null,
    variant: 'primary',
    withBorder: false,
    withRightArrow: false,
    size: 'md'
  };

  state = {
    value: null,
    reCalculateSelection: true
  };

  componentWillReceiveProps() {
    this.setState({
      reCalculateSelection: true
    });
  }

  onStepsChange = value => {
    this.setState({
      value,
      reCalculateSelection: false
    });
  };

  buildChildren() {
    const { children, variant, withBorder, withRightArrow, size } = this.props;
    const { value, reCalculateSelection } = this.state;
    return Children.map(children,
      child => {
        if (!isValidElement(child)) {
          return child;
        }
        const { type: { componentName } } = child;
        switch (componentName) {
          case 'Steps':
            return (
              <div styleName="steps-wrapper">
                {React.cloneElement(child, {
                  onChange: this.onStepsChange,
                  reCalculateSelection,
                  variant,
                  withBorder,
                  withRightArrow,
                  size
                })}
              </div>
            );
          case 'StepperContent':
            return React.cloneElement(child, {
              value,
              variant,
              withBorder,
              size
            });
          default:
            return child;
        }
      }
    );
  }

  render() {
    return (
      <div className={this.props.className}>
        {this.buildChildren()}
      </div>
    );
  }
}

Stepper.Steps = Steps;
Stepper.Step = Step;
Stepper.StepperContent = StepperContent;

export default Stepper;

