import React, {Component} from 'react';
import {connect} from 'react-redux';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import moment from 'moment';
import {Col, Button, Popover, PopoverBody} from 'reactstrap';
import '../../style/InstallationScheduling.css';
import {API_SERVER} from '../../../../config';
import FileDownloader from '../../../../helpers/FileDownloader';
import InstallationSchedulingDatesPerPackage from './InstallationSchedulingDatesPerPackage.jsx';
import {updateInstallationDate} from '../../../../actions/orders/processActions';
import {orderTexts} from '../../../../constants/ordersConstants';

const fileHandler = new FileDownloader();
const fileType = 'installationProtocol';
const status = 'proposed';

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

        this.state = {
            startDate: undefined
        };
        this.toggle = this.toggle.bind(this);
        this.handleDateChange = this.handleDateChange.bind(this);
        this.handleSelect = this.handleSelect.bind(this);
    }

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

    handleDateChange(startDate) {
        this.setState({startDate});
    }

    handleSelect(date, idOrder, idPackage) {
        const newDate = new Date(moment(date).toISOString());
        this.handleDateChange(date);
        this.toggle();

        if(Date.parse(newDate)) {
            const updateDate = moment(date).format('YYYY-MM-DD');
            this.props.dispatch(updateInstallationDate(idOrder, idPackage, updateDate, status, this.handleDateChange));
        }
    }

    downloadDocument(document){
        const fileUrl = `${API_SERVER}/utils/api/downloadFile?idDocument=${document.idDocument}&fileName=${document.documentName}.${document.extension}&fileType=${fileType}`
        const fileName = document.documentName + '.' + document.extension;
        fileHandler.download(fileUrl, fileName);
    }

    render() {
        const acceptedDate = {};
        const proposedDate = {};
        const {
            idOrder,
            idOrderPackagePair,
            orderPackage,
            earliestInstallDate,
            isThisComponentDisabled,
            isPreliminaryInstallationDate,
            installationCompany,
            isInstallationSet
        } = this.props.params.installationParams;
        const {confirmationDates} = this.props;
        const earliestInstallationDate = earliestInstallDate && moment(earliestInstallDate[idOrder]);
        if(confirmationDates && confirmationDates[idOrderPackagePair]) {
            const packageDates = confirmationDates[idOrderPackagePair];
            const accepted = Object.keys(packageDates).find(installDate => {return packageDates[installDate].lastStatus === 'accepted'});
            acceptedDate[idOrderPackagePair] = accepted ? moment(accepted).format('Do MMM, YYYY') : '';
            const proposed = Object.keys(packageDates).find(installDate => {return packageDates[installDate].lastStatus === 'proposed'});
            proposedDate[idOrderPackagePair] = proposed ? moment(proposed).format('Do MMM, YYYY') : '';
        }

        return (
                    <fieldset disabled={isThisComponentDisabled} className="set-installation-dates">
                        <Col>
                            <div className="subtitle">
                            {
                                isPreliminaryInstallationDate[idOrderPackagePair]
                                ? <h6>{orderTexts.labels.PRELIMINARY_INSTALLATION_DATE_LABEL}: </h6>
                                : <h6>{orderTexts.labels.INSTALLATION_DATE}: </h6>
                            }
                            </div>
                            <div id={"installation-scheduler-container-" + idOrderPackagePair} className="install-date-text">
                                {
                                     acceptedDate[idOrderPackagePair]
                                        ? acceptedDate[idOrderPackagePair]
                                        : proposedDate[idOrderPackagePair]
                                            ? proposedDate[idOrderPackagePair]
                                            : (!proposedDate[idOrderPackagePair] && !acceptedDate[idOrderPackagePair]) && orderTexts.labels.NOT_SET
                                }
                            </div>
                        </Col>


                        <Col>
                            <div className="subtitle"><h6>{orderTexts.labels.INSTALL_COMPANY}:</h6></div>
                            <span id={"installation-company-name-" + idOrderPackagePair}>
                                { isInstallationSet[idOrderPackagePair] ? installationCompany[idOrderPackagePair].name : <span>{orderTexts.labels.INSTALL_COMPANY_NOT_SET}</span>}
                            </span>
                        </Col>
                        <Col>
                            <div className="subtitle"><h6>{orderTexts.labels.EARLIEST_INSTALLATION}:</h6></div>
                            <span id={"earliest-installation-date-" + idOrderPackagePair}>
                                {(earliestInstallDate && earliestInstallDate[idOrder])
                                    ? moment(earliestInstallDate[idOrder]).format('Do MMM, YYYY')
                                    : '-'}
                            </span>
                        </Col>
                        <Col>
                            <div className="subtitle"><h6>{orderTexts.labels.PROPOSED_DATES}</h6></div>
                            {
                                confirmationDates && confirmationDates[idOrderPackagePair]
                                && Object.keys(confirmationDates[idOrderPackagePair]).map((confirmationDate) =>
                                    <InstallationSchedulingDatesPerPackage
                                        key={'order-package-installation-dates-' + confirmationDate}
                                        minDate={earliestInstallationDate}
                                        confirmationDate={confirmationDate}
                                        dateInfo={confirmationDates[idOrderPackagePair][confirmationDate]}
                                        orderPackage={orderPackage}
                                        openDialogInstallContent={this.props.params.openDialogInstallContent}
                                        installationParams={this.props.params.installationParams}
                                        isComponentDisabled={isThisComponentDisabled}/>)
                            }
                        </Col>
                        <Col id={"installation-scheduling-propose-date-" + idOrderPackagePair}>
                            <Button id={"propose-new-installation-date-" + idOrderPackagePair} disabled={isThisComponentDisabled} className="propose-new-date-btn" onClick={this.toggle}>Add optional date</Button>
                            <Popover placement="bottom"
                                        isOpen={this.state.popoverOpen}
                                        target={"propose-new-installation-date-" + idOrderPackagePair}
                                        container={"installation-scheduling-propose-date-" + idOrderPackagePair}
                                        className="dates-info-popover"
                                        toggle={this.toggle}>
                               <PopoverBody>
                                   <DatePicker
                                       inline
                                       id={"installation-date-propose-" + idOrderPackagePair}
                                       selected={this.state.startDate}
                                       onSelect={(date) => this.handleSelect(date, orderPackage.idOrder, orderPackage.idPackage)}
                                       minDate={earliestInstallationDate}
                                       dateFormat="Do MMM, YYYY"
                                       placeholderText="Choose a date" />
                               </PopoverBody>
                            </Popover>
                        </Col>
                    </fieldset>

        );
    }
}

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