import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Row, Col, Form, Input} from 'reactstrap';
import {WiaasTable, WiaasTableBody} from '../../mainComponents/table/WiaasTable.jsx';
import ProfileAddressesContainer from '../profileSettings/ProfileAddressesContainer.jsx';
import BillingAddressesContainer from '../profileSettings/BillingAddressesContainer.jsx';
import OrderProjectsSelect from './components/OrderProjectsSelect.jsx';
import {getCustomerDetails,setCartItemsDisabled, nextStep, previousStep, saveOrderDetails, fetchCartItems, setNextActionFct, setPrevActionFct} from '../../actions/cart/cartActions';
import {cartMessages} from '../../constants/cartConstants';
import {updateMessages} from '../../actions/notification/notificationActions';
import {fetchProfileInfo, fetchCountries} from '../../actions/profileSettings/profileSettingsActions';
import {cartTexts} from '../../constants/cartConstants';
import './style/Cart.css';

class CartCustomerDetailsContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            vatCode: '',
            companyName: '',
            details: {
                refernce: '',
                tender: '',
                idProject: ''
            },
            delivery: {},
            billing: {},
            project: {},
            checked: false,
            billingCountry: {}
        };

        this.handleDetailsChange = this.handleDetailsChange.bind(this);
        this.handleDeliveryChange = this.handleDeliveryChange.bind(this);
        this.handleBillingChange = this.handleBillingChange.bind(this);
        this.handleProjectChange = this.handleProjectChange.bind(this);
        this.setBillingAsDelivery = this.setBillingAsDelivery.bind(this);
        this.checkIfInfoCompleted = this.checkIfInfoCompleted.bind(this);
        this.handleNextAction = this.handleNextAction.bind(this);
        this.handlePrevAction = this.handlePrevAction.bind(this);
    }

    componentDidMount() {
        this.props.dispatch(getCustomerDetails());
        this.props.dispatch(fetchCartItems());
        this.props.dispatch(setNextActionFct(this.handleNextAction));
        this.props.dispatch(setPrevActionFct(this.handlePrevAction));
        this.props.dispatch(fetchProfileInfo(this.props.userInfo.wiaas_id_user));
        this.props.dispatch(fetchCountries());
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.customerDetails && nextProps.profileInfo) {
            const selectedDeliveryAddress = nextProps.profileInfo.profileAddresses.find((address) => {
                return address.id === nextProps.customerDetails.details.idDeliveryAddress
            }) || nextProps.profileInfo.profileAddresses[0] || {};

            const selectedBillingAddress = nextProps.profileInfo.billingAddresses.find((address) => {
                return address.id === nextProps.customerDetails.details.idBillingAddress
            }) || nextProps.profileInfo.billingAddresses[0] || {};

            this.setState({
                delivery: selectedDeliveryAddress,
                billing: selectedBillingAddress,
                vatCode: nextProps.profileInfo.vatCode,
                companyName: nextProps.profileInfo.companyName,
                details: nextProps.customerDetails.details
            });
        }
    }

    handleDetailsChange(event) {
        const fieldName = event.target.name;
        const details = this.state.details;
        details[fieldName] = event.target.value;

        return this.setState({details});
    }

    handleDeliveryChange(deliveryAddress) {
        return this.setState({delivery: deliveryAddress});
    }

    handleBillingChange(billingDetails) {
        return this.setState({billing: billingDetails});
    }

    handleProjectChange(project){
        const newDetails = this.state.details;
        newDetails.idProject = project ? project.idProject : null;
        return this.setState({details: newDetails});
    }

    setBillingAsDelivery(e) {
        this.setState({
            checked: !this.state.checked
        });

        setTimeout(() => {
            if (this.state.checked) {
                var newBillingState = Object.assign({}, this.state.billing, this.state.delivery);
                this.props.dispatch(saveOrderDetails({delivery: this.state.delivery, billing: newBillingState, details: this.state.details}, this.props.cartItems));
            }
        }, 10);
    }

    handleNextAction() {
        if(this.checkIfInfoCompleted()) {
            this.props.dispatch(nextStep());
            this.props.dispatch(setCartItemsDisabled(true));
            this.props.dispatch(saveOrderDetails(this.state, this.props.cartItems));
        }
    }

    handlePrevAction() {
        if(this.checkIfInfoCompleted()) {
            this.props.dispatch(previousStep());
            this.props.dispatch(setCartItemsDisabled(false));
            this.props.dispatch(saveOrderDetails(this.state, this.props.cartItems));
        }
    }

    checkIfInfoCompleted() {
        const {delivery, billing} = this.state;
        const isDeliveryAddressCompleted = Object.keys(delivery).length ? Object.keys(delivery).every(delivKey => {
            return delivery[delivKey] !== '';
        }) : false;
        const isBillingAddressCompleted = Object.keys(billing).length ? Object.keys(billing).every(billingKey => {
            return billing[billingKey] !== '' || billingKey === 'firstName' || billingKey === 'lastName' || billingKey === 'invoiceMail';
        }) : false;

        if(isDeliveryAddressCompleted && isBillingAddressCompleted) {
            return true;
        } else {
            this.props.dispatch(updateMessages([
                {
                    code: 'warning',
                    message: 'INFO_INCOMPLETE'
                }
            ], cartMessages));

            return false;
        }
    }

    uncheckSameBillingIfChangesAreMade() {
        if(this.state.checked) {
            this.setState({ checked: !this.state.checked });
        }
    }

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

        return (
            <div id="cart-customer-details-container">
                <WiaasTable id="cart-customer-main-information-container">
                    <WiaasTableBody>
                        <Row className="cart-customer-main-info-row">
                            <Col md="4">{cartTexts.labels.VAT}</Col>
                            <Col md="4">{profileInfo && profileInfo.vatCode}</Col>
                        </Row>
                        <Row className="cart-customer-main-info-row">
                            <Col md="4">{cartTexts.labels.COMPANY}</Col>
                            <Col md="4">{profileInfo && profileInfo.companyName}</Col>
                        </Row>
                        <Row className="cart-customer-main-info-row">
                            <Col md="4">{cartTexts.labels.REFERENCE}</Col>
                            <Input className="col-md-4" id ="reference-nb"  type="text" name="reference" value={this.state.details.reference || ''} onChange={this.handleDetailsChange} />
                        </Row>
                        <Row className="cart-customer-main-info-row">
                            <Col md="4">{cartTexts.labels.BID}</Col>
                            <Input className="col-md-4" id="tender-nb" type="text" name="tender" value={this.state.details.tender || ''} onChange={this.handleDetailsChange} />
                        </Row>
                        <Row className="cart-customer-main-info-row">
                            <Col md="4">{cartTexts.labels.PROJECT}</Col>
                            <OrderProjectsSelect handleChange={this.handleProjectChange} idProject={this.state.details.idProject}/>
                        </Row>
                        {
                            isLoading &&
                            <Row>
                                <Col className="loader">
                                    <i className="fa fa-spinner fa-spin fa-3x" aria-hidden="true"></i>
                                </Col>
                            </Row>
                        }
                        { !isLoading &&
                            <div>
                                <Form id="delivery-information" className="cart-address-box">
                                    {
                                        (profileInfo && !isProfileLoading) &&
                                        <ProfileAddressesContainer
                                            params={{location: 'cart', handleDeliveryChange: this.handleDeliveryChange, idSelectedDeliveryAddress: this.state.delivery.id}}
                                            idUser={this.props.userInfo.wiaas_id_user}/>
                                    }
                                </Form>
                            </div>
                        }

                        { !isLoading &&
                            <div>
                                <Form id="billing-information" className="cart-address-box">
                                    {
                                        (profileInfo && !isProfileLoading) &&
                                        <BillingAddressesContainer
                                            idCompany={profileInfo.idCompany}
                                            params={{location: 'cart', handleBillingChange: this.handleBillingChange, idSelectedBillingAddress: this.state.billing.id}}
                                            idUser={this.props.userInfo.wiaas_id_user}/>
                                    }
                                </Form>
                            </div>
                        }
                    </WiaasTableBody>
                </WiaasTable>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    cartItems: state.cartReducer.cartItems,
    customerDetails: state.cartReducer.customerDetails,
    isLoading: state.cartReducer.isLoading,
    isProfileLoading: state.profileSettingsReducer.isLoading,
    userInfo: state.auth.userInfo,
    profileInfo: state.profileSettingsReducer.profileInfo,
});

export default connect(mapStateToProps)(CartCustomerDetailsContainer);
