import React, { Component } from "react";
import PropTypes from 'prop-types';

import { injectIntl } from 'react-intl';

import PaymentMethods from 'components/PaymentMethods';
import { 
        AbstractForm, 
        ActivityIndicator, 
        Toolbar, 
        ToolbarSection, 
        ToolbarButton, 
        ToolbarButtons, 
        ToolbarRow, 
        ListTitle,
        PortalContainer } from 'lib/components';

import Toast from 'components/Toast';

import backendRequest from 'lib/backend';
import { fromJS } from 'immutable';
import icons from 'constants/icons';
import form from 'lib/form';
import validator from 'lib/validator';

import messages from './messages';
import commonMessages from '../../../messages';

import { fetchEntity, saveEntity, selector } from './redux.js';
import { connect } from 'react-redux';  


class PaymentMethodForm extends AbstractForm {

    constructor(props) {
        super(props);

        this.handleBack = this.handleBack.bind(this);
    }
    
    componentWillMount() {
        this.props.fetchEntity(global.cfg.unitId);
    }

    handleBack() {
        this.context.router.push('/settings');
    }


    render() {
        let { status, intl, submit, onSubmit, onChange, valueOf } = this.props;
        let pending = !!(status && ( status.isFetching || status.isSaving ));
        let formProps = { type: "password" };

        return (
            <form onSubmit={ this.handleSubmit(onSubmit) }>
                <div className="pv10">
                    <Toolbar>
                        <ToolbarSection>
                            <ListTitle 
                                title={ intl.formatMessage(messages.title) }
                                titleIcon=""
                                />
                        </ToolbarSection>
                        <ToolbarButtons>
                            <ToolbarButton 
                                label={ intl.formatMessage({ id: "common.button.back" }) }
                                onClick={ this.handleBack } 
                                >
                                <span className="icon">{ icons.back }</span>
                            </ToolbarButton>
                            <ToolbarButton 
                                label={ intl.formatMessage({ id: "common.button.save" }) }
                                onClick={ submit }
                                >
                                <span className="icon">{ icons.ok }</span>
                            </ToolbarButton>
                        </ToolbarButtons>
                    </Toolbar>

                    <PortalContainer>
                        <div className="pv20">
                            <div className="form">
                                <PaymentMethods 
                                    items={ valueOf("paymentMethods") } 
                                    onChange={ this.props.onChangeHandler("paymentMethods", items => items) }
                                    editName
                                    />
                            </div>
                        </div>
                    </PortalContainer>

                    <ActivityIndicator show={ pending } type="overlay" />
                </div>
            </form>
        );
    }

}


PaymentMethodForm.contextTypes = {
    router: PropTypes.object.isRequired
};


PaymentMethodForm = form(PaymentMethodForm, {
    onValidationFailed: Toast.validationFailed,
    validate: (unit, error) => {
        return true;
        /*
        let valid = true;
        if (!validator.required(unit.currentPassword)) {
            error({ field: "currentPassword", code: "common.validation.requiredField" });
            valid = false;
        }
        if (!validator.required(unit.newPassword)) {
            error({ field: "newPassword", code: "common.validation.requiredField" });
            valid = false;
        }
        if (!validator.required(unit.newPasswordCheck)) {
            error({ field: "newPasswordCheck", code: "common.validation.requiredField" });
            valid = false;
        }
        return valid;
        */
    }
});


class Wrapper extends Component {

    constructor(props) {
        super(props);

        this.handleSave = this.handleSave.bind(this);
    }

    async handleSave(data) {
        let intl = this.props.intl;

        let unitId = global.cfg.unitId;
        try {
            await this.props.saveEntity(unitId, data);  

            Toast.saved();
        } catch (e) {
            Toast.error(e);
        }
    }

    render() {
        return <PaymentMethodForm {...this.props} onSubmit={ this.handleSave } />
    }

}

Wrapper.contextTypes = {
    router: PropTypes.object.isRequired
};

function mapDispatchToProps(dispatch, props) {
    return {
        dispatch,
        fetchEntity: (unitId) => dispatch(fetchEntity(unitId, { unitId })),
        saveEntity: (unitId, data) => dispatch(saveEntity(unitId, data, { unitId }))
    };
}

export default injectIntl(connect(selector, mapDispatchToProps)(Wrapper));
