import React, {Component} from 'react';
import {connect} from 'react-redux';
import WiaasBox from '../../mainComponents/box/WiaasBox.jsx';
import {fetchOrderInfo, getAllDataForInstallation} from '../../actions/orders/processActions';
import OrderInfo from './components/OrderInfo.jsx';
import OrderProcess from './components/process/OrderProcess.jsx';
import ProcessPackage from './components/packages/ProcessPackage.jsx';
import OrderComments from './components/OrderComments.jsx';
import PackagesNav from './components/PackagesNav.jsx';
import PriceHelper from '../../helpers/coMarket/PriceHelper';
import ProcessNavContainer from './ProcessNavContainer.jsx';
import OrderDocuments from './components/OrderDocuments.jsx';
import {orderTexts} from '../../constants/ordersConstants';
import './style/ProcessContainer.css';
import './style/ProcessNavContainer.css';

const priceHelper = new PriceHelper();
const usedForDirective = 'installationScheduling';
const stepsNameForInstallation = {
    firstStepEnabled: 5,
    lastStepEnabled: 6
};
const fileType = 'installationProtocol';

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

        this.onViewChange = this.onViewChange.bind(this);
        this.getActiveView = this.getActiveView.bind(this);
        this.onPackageFilter = this.onPackageFilter.bind(this);
        this.filterPackages = this.filterPackages.bind(this);
        this.state = {
            activeView : 'info',
            packageNameFilter: 'all',
            isSchedulingDisabled: {},
            isOnePackageAndInstallationNotExists: {},
            isInstallationInPackage: {},
            orderPackagePairs: [],
            tooltipOpen: false,
            isScheduleBtnClicked: false
        };
    }

    componentDidMount() {
        this.props.dispatch(fetchOrderInfo(this.props.idOrder));
        //this.props.dispatch(getAllDataForInstallation(this.props.idOrder, usedForDirective, stepsNameForInstallation, fileType));
        const orderPackagePairs = [];
        const isSchedulingDisabled = {};
        isSchedulingDisabled[this.props.idOrder] = true;
        const newState = Object.assign(isSchedulingDisabled, this.state.isSchedulingDisabled);

        if(this.props.orderInfo) {
            this.props.orderInfo.packages.forEach(orderPackage => {
                orderPackagePairs.push(this.props.orderInfo.id + '-' + orderPackage.id);
            });
        }
        this.setState({
            orderPackagePairs,
            isSchedulingDisabled: newState
        });
    }

    componentWillReceiveProps(nextProps) {
        const {installCompanies, isComponentDisabled, earliestInstallDate, areAllShippingDatesConfirmed} = nextProps;
        const allPackagesScheduleInstallDisabled = [];
        const areComponentsDisabled = {};
        const isInstallationSet = {};
        const isOnePackageAndInstallationNotExists = {};
        const isInstallationInPackage = {};

        if(installCompanies && isComponentDisabled && earliestInstallDate) {
            if(nextProps.orderInfo) {
                const idOrder = nextProps.orderInfo.id;
                nextProps.orderInfo.packages.forEach(orderPackage => {
                    const idOrderPackagePair = orderPackage ? idOrder + '-' + orderPackage.id : '';
                    orderPackage.idOrderPackagePair = idOrderPackagePair;
                    areComponentsDisabled[idOrder] = this.checkIfComponentIsDisabled(idOrder, isComponentDisabled, earliestInstallDate);

                    const availableCompanies = {};
                    const selectedCompanies = {};
                    isInstallationSet[idOrderPackagePair] = false;

                    if(installCompanies) {
                        availableCompanies[idOrderPackagePair] = idOrderPackagePair in installCompanies.available ? installCompanies.available[idOrderPackagePair] : [];
                        selectedCompanies[idOrderPackagePair] = idOrderPackagePair in installCompanies.selected ? installCompanies.selected[idOrderPackagePair] : {};
                        if (idOrderPackagePair in selectedCompanies && Object.keys(selectedCompanies[idOrderPackagePair]).length > 0) {
                            isInstallationSet[idOrderPackagePair] = true;
                        }

                        if(availableCompanies[idOrderPackagePair].length === 0 && Object.keys(selectedCompanies[idOrderPackagePair]).length === 0) {
                            isOnePackageAndInstallationNotExists[orderPackage.idOrder] = nextProps.orderInfo.packages.length === 1 ? true : false;
                            isInstallationInPackage[idOrderPackagePair] = false;
                        } else {
                            isInstallationInPackage[idOrderPackagePair] = true;
                        }
                    }

                    const isSchedulingDisabled = areComponentsDisabled[idOrder] || (isInstallationSet && !isInstallationSet[idOrderPackagePair]);
                    allPackagesScheduleInstallDisabled.push(isSchedulingDisabled);
                });

                const isSchedulingDisabled = Object.assign({}, this.state.isSchedulingDisabled);
                isSchedulingDisabled[nextProps.orderInfo.id] = allPackagesScheduleInstallDisabled.every(isDisabled => {return isDisabled === true;});
                this.setState({
                    isSchedulingDisabled,
                    areComponentsDisabled,
                    isInstallationSet,
                    isOnePackageAndInstallationNotExists,
                    isInstallationInPackage,
                    areAllShippingDatesConfirmed,
                    packages: nextProps.orderInfo.packages
                });
            }
        }
    }

    checkIfComponentIsDisabled(idOrder, isComponentDisabled, earliestInstallDate) {
        if(isComponentDisabled && usedForDirective in isComponentDisabled && idOrder in isComponentDisabled[usedForDirective]) {
            const isScheduleComponentDisabled = isComponentDisabled[usedForDirective][idOrder];
            if(earliestInstallDate) {
                return isScheduleComponentDisabled || (!(idOrder in earliestInstallDate) || earliestInstallDate[idOrder] === '-');
            }
        }

        return true;
    }

    calculatetTotalPrice(packages, currency) {
        let fixedPrice = priceHelper.sumPrices(packages.map(pkg => { return pkg.quantity * pkg.price}));
        let recurrentPrice = priceHelper.sumPrices(packages.map(pkg => { return pkg.quantity * pkg.recurringPrice}));
        let servicesPrice = priceHelper.sumPrices(packages.map(pkg => { return pkg.quantity * pkg.servicePrice}));

        return  {
            fixedPrice,
            recurrentPrice: priceHelper.sumPrices([recurrentPrice, servicesPrice]),
            periodUnit: packages[0].periodUnit,
            currency: currency
        }
    }

    onViewChange(activeView){
        this.setState({activeView});
    }

    getActiveView() {
        return this.state.activeView;
    }

    onPackageFilter(packageNameFilter) {
        this.setState({packageNameFilter});
    }

    filterPackages(orderPackage){
        if(this.state.packageNameFilter === 'all') {
            return true;
        }else{
            return orderPackage.name === this.state.packageNameFilter;
        }
    }

    getButtonClass() {
        if(this.props.orderInfo) {
            return this.state.isSchedulingDisabled[this.props.orderInfo.id] ? 'schedule-inactive' : 'schedule-active';
        }

        return 'schedule-inactive';
    }

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

        return (
                <div id="order-info">
                    {
                        isLoading &&
                        <div className="loader">
                            <i className="fa fa-spinner fa-spin fa-3x" aria-hidden="true"></i>
                        </div>
                    }
                    {
                        (orderInfo && !isLoading) &&
                        <div>
                            <WiaasBox
                                customHeader={ProcessNavContainer}
                                customHeaderParams={{
                                    orderInfo: orderInfo,
                                    packages: orderInfo.packages,
                                    onViewChange: this.onViewChange,
                                    getActiveView: this.getActiveView,
                                    installationData: this.state
                                }}>
                                <OrderInfo totalPrice={this.calculatetTotalPrice(orderInfo.packages, orderInfo.currency)} orderDetails={orderInfo} installationData={this.state}/>
                            </WiaasBox>
                            {
                                this.state.activeView !== 'info' &&
                                <div className="components-link">
                                    <div className="link-line"></div>
                                </div>
                            }
                            {
                                this.state.activeView === 'info' &&
                                <OrderProcess
                                    onViewChange={this.onViewChange}
                                    orderStatus={orderInfo.status}
                                    orderProcess={orderInfo.process}/>
                            }
                            {
                                this.state.activeView === 'packages' &&
                                <WiaasBox id="order-packages"
                                        customHeader={PackagesNav}
                                        customHeaderParams={{packages: orderInfo.packages, onPackageFilter: this.onPackageFilter, packageNameFilter: this.state.packageNameFilter}}
                                        >
                                    {
                                        orderInfo.packages.filter(this.filterPackages).map(orderPackage =>
                                            <ProcessPackage key={orderPackage.id}
                                                onViewChange={this.onViewChange}
                                                idCommercialLead={orderInfo.commercialLead.id}
                                                currency={orderInfo.currency}
                                                orderPackage={orderPackage}/>
                                        )
                                    }
                                </WiaasBox>
                            }
                            {
                                this.state.activeView === 'comments' &&
                                <OrderComments orderInfo={orderInfo} orderComments={orderInfo.comments} orderPackages={orderInfo.packages}/>
                            }

                            {
                                this.state.activeView === 'documents' &&
                                <OrderDocuments orderDocumentsBundle={orderInfo.documents} />
                            }
                        </div>
                    }

                    {
                        (!orderInfo && !isLoading) &&
                        <div className="no-rigths">
                            {orderTexts.labels.NOT_AVAILABLE}!
                        </div>
                    }
                </div>
        );
    }
}

const mapStateToProps = (state) => ({
    isCompanyAdmin: state.auth.isCompanyAdmin,
    orderInfo: state.processReducer.orderInfo,
    confirmationDates: state.processReducer.confirmationDates,
    isLoading: state.processReducer.isLoading,
    isNextStepWanted: state.processReducer.isNextStepWanted,
    isComponentDisabled: state.processReducer.isComponentDisabled,
    earliestInstallDate: state.processReducer.earliestInstallDate,
    installCompanies: state.processReducer.installCompanies,
    areAllShippingDatesConfirmed: state.processReducer.areAllShippingDatesConfirmed
});

export default connect(mapStateToProps)(ProcessContainer);
