import React, {Component} from 'react';
import {Col} from 'reactstrap';
import {connect} from 'react-redux';
import './style/CartStepsContainer.css';
import {fetchCartItems} from '../../actions/cart/cartActions';
import {cartTexts} from '../../constants/cartConstants';

class CartStepsContainer extends Component {
    constructor(props) {
        super(props);

        this.handleStepChange = this.handleStepChange.bind(this);
    }

    componentDidMount() {
        const isForSteps = true;
        this.props.dispatch(fetchCartItems(isForSteps));
    }

    handleStepChange(stepDirection) {
        if(stepDirection === 'next') {
            if(this.props.nextStepAction) {
                this.props.nextStepAction();
            }
        } else {
            if(this.props.prevStepAction) {
                this.props.prevStepAction();
            }
        }
    }

    render() {
        const {cartSteps, currentStep, isLoading} = this.props;
        const stepsLength = cartSteps && Object.keys(cartSteps).length - 1;

        return (
            <Col id="cart-steps-container" xl="12" lg="12" md="12" xs="12" sm="12">
                {(cartSteps && cartSteps[currentStep] && cartSteps[currentStep].previous && !isLoading) &&
                    <span onClick={()=>{this.handleStepChange('previous')}} className="prev-btn">
                        <Col sm="12" xs="12">
                            {cartTexts.buttons.BACK}
                        </Col>
                    </span>
                }
                {cartSteps && Object.keys(cartSteps).map((stepKey, index) =>
                    <span key={'cart-step-' + stepKey}>
                        <Col xl="3" sm="12" xs="12" className={'step-name ' + cartSteps[stepKey].status}>
                            {(index + 1) + ' . ' + cartSteps[stepKey].name}
                        </Col>
                        {stepsLength !== index && <div className="steps-link"><div className="step-link"></div></div>}
                    </span>
                )}
                {(cartSteps && cartSteps[currentStep] && cartSteps[currentStep].next && !isLoading) &&
                    <span onClick={()=>{this.handleStepChange('next')}} className="next-btn">
                        <Col sm="12" xs="12" >
                            {cartTexts.buttons.NEXT}
                        </Col>
                    </span>
                }
            </Col>
        );
    }
}

const mapStateToProps = (state) => ({
    cartItems: state.cartReducer.cartItems,
    cartSteps: state.cartReducer.cartSteps,
    currentStep: state.cartReducer.currentStep,
    cartDocuments: state.cartReducer.cartDocuments,
    nextStepAction: state.cartReducer.nextStepAction,
    prevStepAction: state.cartReducer.prevStepAction,
    isLoading: state.cartReducer.isLoading
});

export default connect(mapStateToProps)(CartStepsContainer);
