import React, {Component} from 'react';
import {connect} from 'react-redux';
import Dropzone from 'react-dropzone';
import {Row, Col, Button} from 'reactstrap';
import {fetchCustomerAcceptance, uploadAcceptance, acceptDeclineInstallation, badFile} from '../../../../actions/orders/customerAcceptanceActions';
import {setDialogContent, setDialogOpenFlag} from '../../../../actions/dialog/dialogActions';
import AcceptanceDeclineReason from './AcceptanceDeclineReason.jsx';
import FileDownloader from '../../../../helpers/FileDownloader';
import {orderTexts} from '../../../../constants/ordersConstants';
import '../../style/CustomerAcceptance.css';

const fileHandler = new FileDownloader();

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

        this.state = {
            reason : '',
            actionType : ''
        }

        this.acceptDeclineInstallation = this.acceptDeclineInstallation.bind(this);
        this.onEditorChange = this.onEditorChange.bind(this);
    }

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

    uploadFile(idEntry, acceptedFiles, rejectedFiles) {
        if(acceptedFiles && acceptedFiles.length){
            const file = acceptedFiles[0];
            this.props.dispatch(uploadAcceptance(idEntry, file));
        }

        if(rejectedFiles && rejectedFiles.length) {
            this.props.dispatch(badFile());
        }
    }

    getAcceptanceStatusClass(acceptance, daysDiff) {
        const statuses = {
            0 : 'waiting',
            1 : 'accepted',
            '-1' : 'declined'
        };

        if(acceptance === 0 && daysDiff <= 0){
            return 'danger';
        } else if(acceptance === 0 && daysDiff <= 3) {
            return 'warning';
        }else{
            return statuses[acceptance];
        }
    }

    acceptDeclineInstallation() {
        const {idProcess} = this.props.step;
        const {actionType, reason} = this.state;
        this.props.dispatch(acceptDeclineInstallation(idProcess, actionType, reason));
        this.setState({reason: ''});
    }

    getAcceptanceMessage(customerAcceptance){
        const messages = {
            0 : orderTexts.labels.NOT_ACCEPTED + (customerAcceptance.acceptanceDueDate || orderTexts.labels.NOT_SET),
            1 : orderTexts.labels.ACCEPTED,
            '-1' : orderTexts.labels.DECLINED
        }

        return messages[customerAcceptance.status];
    }

    onEditorChange(reason) {
        this.setState({reason});
    }

    openDialog(actionType) {
        const dialogContent = this.getAcceptanceDialog(actionType);
        this.setState({actionType});
        this.props.dispatch(setDialogOpenFlag(true));
        this.props.dispatch(setDialogContent(dialogContent));
    }

    getAcceptanceDialog(actionType) {
        return {
            buttons: [
                {
                    color: 'success',
                    action: this.acceptDeclineInstallation,
                    name: orderTexts.buttons.SEND,
                    id: 'confirm-acceptance'
                }, {
                    color: 'secondary',
                    name: orderTexts.buttons.CANCEL,
                    id: 'cancel-acceptance'
                }
            ],
            header: orderTexts.labels.ACCEPTANCE_HEADER,
            TagName: AcceptanceDeclineReason,
            params: {onEditorChange: this.onEditorChange, actionType}
        };
    }

    componentDidMount(){
        const {idProcess} = this.props.step;
        this.props.dispatch(fetchCustomerAcceptance(idProcess));
    }

    render() {
        const {step} = this.props;
        const customerAcceptance = this.props.customerAcceptance || null;

        return (
            <div id="customer-acceptance" className="validate-questionnaire">
                {
                    customerAcceptance &&
                    <Row>
                        <Col className="aceeptance-message">
                            {this.getAcceptanceMessage(customerAcceptance)} <div className={'status-icon ' + this.getAcceptanceStatusClass(customerAcceptance.status, customerAcceptance.daysDiff)}></div>
                        </Col>
                    </Row>
                }
                {
                    (customerAcceptance && customerAcceptance.status === -1) &&
                    <Row>
                        <Col>{orderTexts.labels.REASON}: {customerAcceptance.decline_reason}</Col>
                    </Row>
                }
                <Row className="acceptance-docs">
                    <Col xl="4" lg="5" md="4">
                        <Dropzone className="upload-file-drop-zone"
                                multiple={false}
                                accept=".pdf,.docx,.doc,.xlsx,.xls,.odt,.ods,.jpg,.png,.jpeg"
                                activeClassName="upload-file-accept"
                                onDrop={(acceptedFiles, rejectedFiles)=>{this.uploadFile(step.idProcess, acceptedFiles, rejectedFiles)}}>
                             <h5 className="drop-zone-text">{orderTexts.labels.UPLOAD_ACCEPTANCE_LABEL}</h5>
                        </Dropzone>
                    </Col>
                    <Col xl="4" lg="7" md="8">
                        {
                            (customerAcceptance && customerAcceptance.documents && customerAcceptance.documents.length > 0) &&
                            <div>
                                {
                                    customerAcceptance.documents.map((document, index) => <div key={'acceptance-documnet-' + index}>
                                        <span className="document-link">
                                            <i className={'fa fa-file'}></i> <a target="_blank" href={document.url}> {document.name} ({document.extension}) </a>
                                        </span>
                                        <span className="document-status">
                                            {document.validation} <div className={'status-icon ' + document.validation}></div>
                                        </span>
                                    </div>)
                                }
                            </div>
                        }
                        {
                            (customerAcceptance && (!customerAcceptance.documents || customerAcceptance.documents.length === 0) ) &&
                            <div>
                                {orderTexts.labels.NO_DOCUMENTS_UPLOADED}
                            </div>
                        }
                    </Col>
                </Row>
                <Row>
                    <Col className="acceptance-label" xl="12" lg="12" md="12" xs="12">
                        {orderTexts.labels.ACCEPTANCE_LABEL}
                    </Col>
                    <Col lg="7">
                        <Button onClick={()=>{this.openDialog('accept')}}
                            id="acceptance-accept"
                            color="secondary"
                            className="acceptance-button acceptance-accept">{orderTexts.buttons.ACCEPT_INSTALLATION}</Button>
                        <Button onClick={()=>{this.openDialog('decline')}}
                            id="acceptance-decline"
                            color="secondary"
                            className="acceptance-button acceptance-decline">{orderTexts.buttons.DECLINE_INSTALLATION}</Button>
                    </Col>
                </Row>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    customerAcceptance: state.processReducer.customerAcceptance
});

export default connect(mapStateToProps)(CustomerAcceptance);
