import React, {Component} from 'react';
import {connect} from 'react-redux';
import 'react-datepicker/dist/react-datepicker.css';
import moment from 'moment';
import {Row, Col, Button, Popover, PopoverBody} from 'reactstrap';
import '../../style/InstallationScheduling.css';
import {updateInstallationDate, removeMyDate, setSchedulingFlag} from '../../../../actions/orders/processActions';
import {setDialogContent, setDialogOpenFlag} from '../../../../actions/dialog/dialogActions';
import {orderTexts} from '../../../../constants/ordersConstants';

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

        this.state = {
          startDate: undefined,
          btnType: '',
          nestedModal: false,
          closeAll: false,
          popoverOpen: false
        };
        this.toggle = this.toggle.bind(this);
        this.openInstallationDialog = this.openInstallationDialog.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleBtnClick = this.handleBtnClick.bind(this);
        this.handleBtnAction = this.handleBtnAction.bind(this);
    }

    componentDidMount() {
        this.props.dispatch(setSchedulingFlag(this.props.installationParams.isSchedulingDisabled));
    }

    handleChange(date) {
        this.setState({startDate: date});
    }

    toggle() {
        this.setState({
          popoverOpen: !this.state.popoverOpen
        });
    }

    canUserAcceptOrDecline(dateInfo, lastStatus) {
        let additionalCondition = false;
        if (lastStatus === 'declined') {
            additionalCondition = dateInfo.lastStatus === 'canceled' && dateInfo.isProposedByMe;
        }
        return !this.props.isComponentDisabled &&
            ((dateInfo.lastStatus === 'proposed' && !dateInfo.isProposedByMe) ||
                (dateInfo.lastStatus === lastStatus && dateInfo.isProposedByMe) ||
                additionalCondition);
    }

    isDateProposedByMe() {
        return this.props.dateInfo.lastStatus === 'proposed' && this.props.dateInfo.isProposedByMe === true;
    }

    isRemoveBtnVisible(confirmationDate) {
        return !this.props.isComponentDisabled && this.isDateProposedByMe();
    }

    handleBtnClick(type) {
        this.setState({type});
        const upperCaseType = type.charAt(0).toUpperCase() + type.slice(1);
        const dialogInstallationContent = {
            buttons: [
                {
                    color: 'success',
                    action: this.handleBtnAction,
                    name: orderTexts.buttons.YES,
                    id: type + '-installation-date-confirmation'
                }, {
                    color: 'secondary',
                    name: orderTexts.buttons.NO,
                    action: this.openInstallationDialog,
                    id: 'cancel-' + type + '-installation-date'
                }
            ],
            header: upperCaseType + ' installation date confirmation',
            body: 'Are you sure you want to ' + type + ' the installation date proposed?'
        };

        this.props.dispatch(setDialogOpenFlag(true));
        this.props.dispatch(setDialogContent(dialogInstallationContent));
    }

    openInstallationDialog() {
        this.props.openDialogInstallContent(this.props.installationParams);
    }

    handleBtnAction() {
        let handleFunction = this.state.type === 'remove' ? removeMyDate : updateInstallationDate;
        this.props.dispatch(handleFunction(this.props.orderPackage.idOrder, this.props.orderPackage.idPackage, this.props.confirmationDate, this.state.type));
        this.openInstallationDialog();
    }

    getStatusIcon(status) {
        const statusesIcons = {
            proposed: 'clock-o',
            accepted: 'check',
            canceled: 'remove',
            declined: 'ban',
            invalid: 'remove'
        };

        return 'status-icon-installation-dates fa fa-' + statusesIcons[status];
    }

    render() {
        const {confirmationDate, dateInfo, orderPackage} = this.props;
        const idOrderPackageDatePair = orderPackage.idOrder + '-' + orderPackage.idPackage + '-' + confirmationDate;

        return (
            <div id={"installation-scheduling-dates-container-" + idOrderPackageDatePair} className="installation-scheduling-dates-container">
                <span className="installation-date">
                    <span className={this.getStatusIcon(dateInfo.lastStatus) + ' confirmation-' + dateInfo.lastStatus}></span>
                    <span className="installation-date-proposed">{moment(confirmationDate).format('Do MMM, YYYY')}</span>
                    <i className="dates-info-btn fa fa-info-circle"
                        id={'dates-info-' + idOrderPackageDatePair}
                        onClick={this.toggle}></i>
                    <Popover placement="bottom"
                                isOpen={this.state.popoverOpen}
                                target={'dates-info-' + idOrderPackageDatePair}
                                container={"installation-scheduling-dates-container-" + idOrderPackageDatePair}
                                className="dates-info-popover"
                                toggle={this.toggle}>
                       <PopoverBody>
                           { dateInfo && dateInfo.details &&
                               dateInfo.details.map((details) =>
                                <Row key={'confirmation-date-details-' + details.currentDate}>
                                   <Col>
                                       {moment(details.currentDate).format('Do MMM, YYYY LT')}
                                   </Col>
                                   <Col className={"confirmation-" + details.status}>
                                       <span className={this.getStatusIcon(details.status)}></span>
                                       {details.status}
                                   </Col>
                                   <Col>
                                       {details.username} ({details.userType})
                                   </Col>
                               </Row>
                           )}
                       </PopoverBody>
                    </Popover>
                </span>
                <span className="confirmation-dates-buttons">
                    { this.canUserAcceptOrDecline(dateInfo, 'declined') &&
                        <Button id={"accept-date-"+idOrderPackageDatePair} className="installation-button install-btn-accept" onClick={() => {this.handleBtnClick('accept')}} >{orderTexts.buttons.ACCEPT}</Button>
                    }
                    { this.canUserAcceptOrDecline(dateInfo, 'accepted') &&
                        <Button id={"decline-date-"+idOrderPackageDatePair} className="installation-button install-btn-decline" onClick={() => {this.handleBtnClick('decline')}} >{orderTexts.buttons.DECLINE}</Button>
                    }
                    { this.isRemoveBtnVisible(confirmationDate) &&
                        <Button id={"cancel-remove-installation-dates-"+idOrderPackageDatePair} className="installation-button install-btn-remove" onClick={() => {this.handleBtnClick('remove')}} >{orderTexts.buttons.REMOVE}</Button>
                    }
                </span>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    confirmationDates: state.processReducer.confirmationDates
});
export default connect(mapStateToProps)(InstallationSchedulingDatesPerPackage);
