import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Input, Tooltip, Row, Col} from 'reactstrap';
import '../style/Cart.css';
import {updateMessages} from '../../../actions/notification/notificationActions';
import {updateQuantity, removeCartItem} from '../../../actions/cart/cartActions';
import {setDialogContent, setDialogOpenFlag} from '../../../actions/dialog/dialogActions';
import {cartMessages, cartTexts} from '../../../constants/cartConstants';
import PackageBids from './PackageBids.jsx';

class CartItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tooltipOpen: false,
            itemQuantity: 1,
            idCart: 0
        };

        this.toggleTooltip = this.toggleTooltip.bind(this);
        this.removeItemFromCart = this.removeItemFromCart.bind(this);
        this.resetQuantity = this.resetQuantity.bind(this);
        this.sumPrices = this.sumPrices.bind(this);
    }

    componentWillReceiveProps(nextProps) {
      this.setState({itemQuantity: nextProps.cartItem.quantity});
      this.sumPrices(nextProps.cartItem, nextProps.cartItem.quantity);
    }

    componentDidMount() {
        this.setState({itemQuantity: this.props.cartItem.quantity});
        this.sumPrices(this.props.cartItem, this.props.cartItem.quantity);
    }

    isQuantityValid(quantity) {
        return quantity > 0 && quantity <= 100;
    }

    updateQuantity(cartItem, quantity) {
        if(quantity) {
            this.setState({itemQuantity: quantity});
            if(this.isQuantityValid(quantity)) {
                this.sumPrices(cartItem, quantity);
                this.props.dispatch(updateQuantity(cartItem, quantity));
            } else {
                this.props.dispatch(updateMessages([{code: 'error', message: 'INVALID_QUANTITY'}], cartMessages));
            }
        } else {
            this.setState({itemQuantity: ''});
        }
    }

    resetQuantity(cartItem) {
        if(!this.state.itemQuantity || !this.isQuantityValid(this.state.itemQuantity)) {
            this.updateQuantity(cartItem, 1);
        }
    }

    removeItemFromCart() {
        this.props.dispatch(removeCartItem(this.state.idCart));
    }

    setDialogParams(cartItem, dialogContent) {
        this.setState({idCart: cartItem.idCart});
        this.props.dispatch(setDialogOpenFlag(true));
        dialogContent.bodyVariable = cartItem.packageName;
        this.props.dispatch(setDialogContent(dialogContent));
    }

    toggleTooltip() {
        this.setState({
            tooltipOpen: !this.state.tooltipOpen
        });
    }

    sumPrices(cartItem, quantity) {
        let total = 0;
        let oldTotal = null;
        let totalRecurrent = 0;
        let oldTotalRecurrent = null;
        const selectedBid = cartItem.bids.find((bid) => {
            return cartItem.idSelectedBid === bid.idBid;
        });

        if(selectedBid){
            total += selectedBid.fixedPrice;
            totalRecurrent += selectedBid.servicesPrice + selectedBid.recurrentPrice;

            oldTotal = cartItem.fixedPrice;
            oldTotalRecurrent = cartItem.servicesPrice + cartItem.recurentPrice;
        }else{
            total += cartItem.fixedPrice;
            totalRecurrent += cartItem.servicesPrice + cartItem.recurentPrice;
        }

        if(cartItem.options.length) {
            cartItem.options.forEach((packageOption) => {
                if(Object.keys(packageOption.prices).length) {
                    total += parseFloat(packageOption.prices.fixedExtra);
                    totalRecurrent += parseFloat(packageOption.prices.recurentExtra) + parseFloat(packageOption.prices.servicesExtra);
                }
            });
        }
        if(cartItem.additionalPackages.length) {
            cartItem.additionalPackages.forEach((additionalPackage) => {
                if(Object.keys(additionalPackage).length) {
                    total += parseFloat(additionalPackage.prices.fixedExtra);
                    totalRecurrent += parseFloat(additionalPackage.prices.recurentExtra) + parseFloat(additionalPackage.prices.servicesExtra);
                }
            });
        }

        this.setState({
            fixedPrice: total * quantity,
            recurrentPrice: totalRecurrent * quantity,
            fixedOldPrice: oldTotal !== null ? oldTotal * quantity : null,
            recurrentOldPrice: oldTotalRecurrent !== null ? oldTotalRecurrent * quantity: null
        });
    }

    getPriceClass(price){
        return price !== null ? 'new-price' : 'price';
    }

    render() {
        const dialogContent = {
            buttons: [
                {
                    color: 'success',
                    action: this.removeItemFromCart,
                    name: cartTexts.buttons.YES,
                    id: 'remove-item-confirmation'
                }, {
                    color: 'secondary',
                    name: cartTexts.buttons.CANCEL,
                    id: 'cancel-remove-item'
                }
            ],
            header: cartTexts.labels.REMOVE_ITEM_HEADER,
            body: cartTexts.labels.REMOVE_ITEM_TEXT
        };
        const {cartItem, isFormDisabled} = this.props;
        const cartItemNo = this.props.cartItemNo ? this.props.cartItemNo + 1 : 1;

        return (
            <div id={"item-row-in-cart-" + cartItem.idCart} className="cart-show-items">
                <Row className="cart-item-details">
                    <Col id={"item-package-name-" + cartItem.idCart}
                        xl="8" lg="8" md="7" sm="12" xs="12"
                        className="item-name">
                        {cartItemNo}. {cartItem.packageName}
                        <PackageBids idSelectedBid={cartItem.idSelectedBid} idCart={cartItem.idCart} bids={cartItem.bids}/>
                    </Col>
                    <Col xl="3" lg="3" md="3" sm="9" xs="9" id={"item-quantity-" + cartItem.idCart}>
                        { isFormDisabled
                            ? cartItem.quantity === 1
                                ? cartItem.quantity + ' pc'
                                : cartItem.quantity + ' pcs'
                            : <Input className="quantity-field"
                                value={this.state.itemQuantity}
                                type="number"
                                step="1"
                                onChange={e => this.updateQuantity(cartItem, e.target.value)}
                                onBlur={e => this.resetQuantity(cartItem, e.target.value)}
                                />
                        }
                    </Col>
                    <Col id={"item-remove-btn-" + cartItem.idCart} xl="1" lg="1" md="1" sm="1" xs="1">
                        <i id={'remove-item-' + cartItem.idCart + '-' + cartItem.idPackage}
                            className="fa fa-times remove-item"
                            aria-hidden="true"
                            onClick={() => this.setDialogParams(cartItem, dialogContent) }></i>
                        <Tooltip target={'remove-item-' + cartItem.idCart + '-' + cartItem.idPackage}
                            placement="bottom"
                            isOpen={this.state.tooltipOpen}
                            toggle={this.toggleTooltip}>
                            {cartTexts.labels.REMOVE_FROM_CART}
                        </Tooltip>
                    </Col>
                </Row>
                { (!cartItem.areAdditionalAvailable || !cartItem.areOptionsAvailable || cartItem.status === 'not-available') &&
                    <Row className="cart-item-small-details">
                        <Col id={"item-warning-sign-remove-package-name-" + cartItem.idPackage}
                            xl="12" lg="12" md="12" sm="12" xs="12"
                            className="not-available">
                            {cartTexts.labels.PACKAGE_UNAVAILABLE}
                        </Col>
                    </Row>
                }
                {cartItem.options.length > 0 &&
                    cartItem.options.map((packageOption) =>
                        <Row className="cart-item-small-details" key={"package-option-" + cartItem.idCart + "-" + packageOption.idOptionPackage}>
                            <Col lg={{offset: 1, size: 4}} xs={{offset: 1, size: 4}}>
                                {packageOption.groupName}:
                            </Col>
                            <Col lg="7" xs="7" id={"item-option-" + cartItem.idCart + "-" + packageOption.idOptionPackage}>
                                {packageOption.packageName}
                            </Col>
                        </Row>
                    )
                }
                {cartItem.additionalPackages.length > 0 &&
                    cartItem.additionalPackages.map((additionalPackage) =>
                        <Row className="cart-item-small-details" key={"additional-package-" + cartItem.idCart + "-" + additionalPackage.idAdditionalPackage}>
                            <Col lg={{offset: 1, size: 4}} xs={{offset:1, size: 4}}>
                                {cartTexts.labels.ADDITIOONAL_PACKAGE}:
                            </Col>
                            <Col lg="7" xs="7" id={"item-additional-" + cartItem.idCart + "-" + additionalPackage.idAdditionalPackage}>
                                {additionalPackage.packageName}
                            </Col>
                        </Row>
                    )
                }
                <Row className="cart-item-small-details">
                    <Col lg={{offset: 1, size: 4}} xs={{offset:1, size: 4}}>Payment type:</Col>
                    <Col lg="7" xs="7" id={"item-payment-type-" + cartItem.idCart}>
                        {cartItem.payType}
                    </Col>
                </Row>
                <Row className="cart-item-small-details">
                    <Col lg={{offset: 1, size: 4}} xs={{offset:1, size: 4}}>Price:</Col>
                    <Col lg="7" xs="7" id={"item-price-" + cartItem.idCart}>
                        <table className="price-table">
                            <thead>
                                <tr>
                                    <th>{cartTexts.labels.ON_DELIVERY}</th>
                                    <th>{cartTexts.labels.MONTHLY}</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>
                                        {
                                            this.state.fixedPrice &&
                                            <div>
                                                {
                                                    this.state.fixedOldPrice !== null &&
                                                    <div className="old-price">{this.state.fixedOldPrice}</div>
                                                }
                                                <div className={this.getPriceClass(this.state.fixedOldPrice)}>
                                                    {this.state.fixedPrice.toLocaleString() + ' ' + cartItem.country.currency}
                                                </div>
                                            </div>

                                        }
                                    </td>
                                    <td>
                                        {
                                            this.state.recurrentPrice &&
                                            <div>
                                                {
                                                    this.state.recurrentOldPrice !== null &&
                                                    <div className="old-price">{this.state.recurrentOldPrice}</div>
                                                }
                                                <div className={this.getPriceClass(this.state.recurrentOldPrice)}>
                                                    {this.state.recurrentPrice.toLocaleString() + ' ' + cartItem.country.currency}
                                                </div>
                                            </div>
                                        }
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </Col>
                </Row>
            </div>
        );
    }
}

export default connect()(CartItem);
