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';
import {coMarketTexts} from "../../../constants/coMarketConstants";

class CartItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tooltipOpen: false,
            itemQuantity: 1,
            key: 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 <= 65000;
    }

    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.key));
    }

    setDialogParams(cartItem, dialogContent) {
        this.setState({key: cartItem.key});
        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.recurrentPrice;
        }else{
            total += cartItem.fixedPrice;
            totalRecurrent += cartItem.servicesPrice + cartItem.recurrentPrice;
        }

        if(cartItem.options.length) {
            cartItem.options.forEach((packageOption) => {
                if(Object.keys(packageOption.prices).length) {
                    total += parseFloat(packageOption.prices.fixedExtra);
                    totalRecurrent += parseFloat(packageOption.prices.recurrentExtra) + 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.recurrentExtra) + 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 (
            <Row id={"item-row-in-cart-" + cartItem.key} className="cart-show-items">
                <Col className="">
                    <Row className="cart-item-details justify-content-between">
                        <Col id={"item-package-name-" + cartItem.key}
                             xl="8" lg="8" md="7" sm="12"
                             className="item-name">
                            {cartItem.packageName}
                            <PackageBids idSelectedBid={cartItem.idSelectedBid} key={cartItem.key} bids={cartItem.bids}/>
                        </Col>
                        <Col xl="4" lg="4" md="5" sm="12">
                            <Row className="flex-nowrap justify-content-end">
                                <Col
                                    id={"item-quantity-" + cartItem.key}
                                    className="item-quantity col-auto"
                                >
                                    { 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>
                                { !isFormDisabled && <div className="wiaas-divider"></div> }
                                {
                                    !isFormDisabled && (<Col className="d-flex align-items-center col-auto">
                                        <i id={'remove-item-' + cartItem.key + '-' + cartItem.idPackage}
                                           className="fa fa-trash-o remove-item"
                                           aria-hidden="true"
                                           onClick={() => this.setDialogParams(cartItem, dialogContent) }></i>
                                        <Tooltip target={'remove-item-' + cartItem.key + '-' + cartItem.idPackage}
                                                 placement="bottom"
                                                 isOpen={this.state.tooltipOpen}
                                                 toggle={this.toggleTooltip}>
                                            {cartTexts.labels.REMOVE_FROM_CART}
                                        </Tooltip>
                                    </Col>)
                                }
                            </Row>
                        </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 flex-column"
                            key={"package-option-" + cartItem.key + "-" + packageOption.idOptionPackage}
                        >
                            <span className="cart-item-additional-title">
                                {packageOption.groupName}:
                            </span>
                            <span id={"item-option-" + cartItem.key + "-" + packageOption.idOptionPackage}>
                                {packageOption.packageName}
                            </span>
                        </Row>
                    )
                    }
                    {
                        cartItem.additionalPackages.length > 0 && <Row className="cart-item-small-details flex-column">
                            <span className="cart-item-additional-title">
                                {cartTexts.labels.ADDITIOONAL_PACKAGE}:
                            </span>
                            {
                                cartItem.additionalPackages.map((additionalPackage) =>
                                        <span
                                            key={"item-additional-" + cartItem.key + "-" + additionalPackage.idAdditionalPackage}
                                            id={"item-additional-" + cartItem.key + "-" + additionalPackage.idAdditionalPackage}
                                        >
                                        {additionalPackage.packageName}
                                    </span>
                                )
                            }
                        </Row>
                    }
                    <Row className="cart-item-small-details item-price">
                        <Col className="d-flex align-items-center col-3 item-price-type">
                            <span className="item-price-type">{cartItem.payType}:</span>
                        </Col>
                        <Col className="d-flex">
                            <div className="d-flex flex-column flex-grow-1">
                                <div className="d-flex flex-grow-1 no-wrap item-price-header">
                                    <Col>
                                        <span>{cartTexts.labels.ON_DELIVERY}:</span>
                                    </Col>
                                    <Col>
                                        <span>{cartTexts.labels.MONTHLY}:</span>
                                    </Col>
                                </div>
                                <div className="d-flex flex-grow-1 no-wrap item-price-value">
                                    <Col>
                                        {
                                            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>

                                        }
                                    </Col>
                                    <Col>
                                        {
                                            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>
                                        }
                                    </Col>
                                </div>
                            </div>
                        </Col>
                    </Row>
                </Col>
            </Row>
        );
    }
}

export default connect()(CartItem);
