import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Container, Row, Alert, Col} from 'reactstrap';
import OrderCentralContainer from './OrderCentralContainer.jsx';
import NextActionsContainer from './NextActionsContainer.jsx';
import {fetchGadgets} from '../../actions/dashboard/dashboardActions';
import {setOrderPlacedFlag, setOrderPlacedRedirectFlag} from '../../actions/cart/cartActions';
import {dashboardTexts} from '../../constants/dashboardConstants';
import './Dashboards.css';

const gadgetContainers = {
    CustomerOrderCentral : OrderCentralContainer,
    CustomerNextActions: NextActionsContainer
}

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

        this.state = {
            orderPlaced: this.props.orderPlaced || false,
            redirect: this.props.orderPlacedRedirect || true
        };
    }

    componentDidMount() {
        this.props.dispatch(fetchGadgets());
        if(this.state.orderPlaced && this.state.redirect) {
            this.setState({redirect: false});
            this.props.dispatch(setOrderPlacedRedirectFlag(false));
        }
    }

    render() {
        const {gadgets} = this.props;

        if(this.state.orderPlaced) {
            setTimeout(() => {
                this.setState({orderPlaced: false});
                this.props.dispatch(setOrderPlacedFlag(false));
            }, 15000);
        }

        return (
            <div id="dashboard-container">
                <Container fluid={true} id="dashborad-gadgets">
                    <Row>
                    {
                        this.state.orderPlaced &&
                            <Col>
                                <Alert color="success" className="order-placed-message">
                                    {dashboardTexts.messages.ORDER_PLACED}
                                </Alert>
                            </Col>
                    }
                    </Row>
                    <Row>
                        {
                            gadgets &&
                            gadgets.map((gadget, Key) => {
                                const containerKey = gadget.name.replace(/\s/g, '');
                                if(gadgetContainers[containerKey]){
                                    const TagName = gadgetContainers[containerKey];
                                    return <TagName key={gadget.idGadget} gadget={gadget}/>;
                                }

                                return '';
                            })
                        }
                    </Row>
                </Container>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    gadgets: state.dashboardReducer.gadgets,
    orderPlaced: state.cartReducer.orderPlaced,
    orderPlacedRedirect: state.cartReducer.orderPlacedRedirect
});

export default connect(mapStateToProps)(DashboardsContainer);
