import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Col} from 'reactstrap';
import {Link} from 'react-router-dom';
import {fetchOrders} from '../../actions/dashboard/ordersActions';
import WiaasBox from '../../mainComponents/box/WiaasBox.jsx';
import OrdersList from './components/OrdersList.jsx';
import OrderListHeader from '../orders/components/OrderListHeader.jsx';
import {dashboardTexts} from '../../constants/dashboardConstants';
import './OrderCentral.css';

const type = 'overview';

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

        this.state = {
            orders: [],
            isViewAllOrdersChecked: false
        };
    }

    componentDidMount() {
        this.props.dispatch(fetchOrders());
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.isViewAllOrdersChecked[type] !== this.state.isViewAllOrdersChecked) {
            this.setState({
                isViewAllOrdersChecked: nextProps.isViewAllOrdersChecked[type] || false
            });
            this.props.dispatch(fetchOrders(nextProps.isViewAllOrdersChecked[type]));
        }
        this.setState({
            orders: nextProps.orders
        });
    }

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

        return (<Col xl="8" lg="8" md="12" sm="12" xs="12">
                <WiaasBox id="order-central-gadget" mainTitle={dashboardTexts.labels.ORDER_CENTRAL}  customHeader={OrderListHeader} customHeaderParams={type}>
                {
                    isLoading &&
                    <div className="loader">
                        <i className="fa fa-spinner fa-spin fa-3x" aria-hidden="true"></i>
                    </div>
                }
                {
                    (this.state.orders && this.state.orders.length > 0 && !isLoading) ?
                    <OrdersList orders={this.state.orders} isViewAllOrdersChecked={this.props.isViewAllOrdersChecked[type]}/> :
                    <div className="dashborad-message">
                        <Link to='/co-market'>{dashboardTexts.labels.NO_ORDERS}</Link>
                    </div>
                }
                </WiaasBox>
        </Col>);
    }
}

const mapStateToProps = (state) => ({
    orders: state.ordersCentralReducer.orders,
    isLoading: state.ordersCentralReducer.isLoading,
    isViewAllOrdersChecked: state.ordersReducer.isViewAllOrdersChecked
});

export default connect(mapStateToProps)(OrderCentralContainer);
