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

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

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

import TemplateSelector from 'components/TemplateSelector';

import Toast from 'components/Toast';

import icons from 'constants/icons';
import messages from './messages';
import form from 'lib/form';


class CustomizationForm extends AbstractForm {


    render() {
        let { intl, errors, disabled, unit, unitId, valueOf, onChangeHandler } = this.props;
        let formProps = { disabled };

        return (
            <div className={ `form ${this.props.className}` }>

                <Tabs className="mb20">
                    <Tab title={ intl.formatMessage(messages.tabInvoice) } className="container-max-1200 form" titleDecorator={ <ErrorBubble errors={ errors } fields={ ["name", "expenseDate", "totalAmount", "totalPayable"] }/> }>
                        { this.renderField("invoiceThankYouNote", intl.formatMessage(messages.defaultThankYouNote), formProps) }

                        <TemplateSelector 
                            unit={ unit } 
                            template={ valueOf("invoiceTemplate") } 
                            onChangeTemplate={ onChangeHandler("invoiceTemplate", v => v) }
                            templateLang={ valueOf("invoiceLang") }
                            defaultLang={ unit.locale }
                            onChangeLanguage={ onChangeHandler("invoiceLang", v => v) }
                            unitId={ unitId }
                            />
                    </Tab>
                   
                    <Tab title={ intl.formatMessage(messages.tabEmail) } className="container-max-900 form" titleDecorator={ <ErrorBubble errors={ errors } fields={ ["name", "expenseDate", "totalAmount", "totalPayable"] }/> }>
                        <div className="row">
                            <div className="col-sm-6">
                                { this.renderField("emailSenderAddress", intl.formatMessage(messages.emailSenderAddress), formProps) }
                            </div>
                        </div>

                        <div className="pv10">
                            { this.renderField("invoiceEmailSubject", intl.formatMessage(messages.emailInvoiceSubject), formProps) }
                        </div>

                        { this.renderField("invoiceEmailTitle", intl.formatMessage(messages.emailInvoiceTitle), formProps) }
                        { this.renderTextArea("invoiceEmailMessage", intl.formatMessage(messages.emailInvoiceBody), formProps) }

                        <div className="row">
                            <div className="col-sm-6">
                                { this.renderTextArea("emailSignature", intl.formatMessage(messages.emailSignature), formProps) }
                            </div>
                        </div>
                    </Tab>
                </Tabs>

            </div>
        );
    }

}


CustomizationForm = form(CustomizationForm);

class Customization extends Component {

    constructor(props) {
        super(props);

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


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


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


    handleSubmit() {
        this.refs.form.submit();
    }


    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() {
        let status = this.props.status;
        let pending = !!(status && ( status.isFetching || status.isSaving ));
        let intl = this.props.intl;

        let { unit, unitId } = this.props;

        return (
            <div className="pv10">
                <Toolbar>
                    <ToolbarSection>
                        <ListTitle 
                            title={ intl.formatMessage(messages.title) }
                            titleIcon={ icons.customizationSettings }
                            />
                    </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={ this.handleSubmit } 
                            >
                            <span className="icon">{ icons.ok }</span>
                        </ToolbarButton>
                    </ToolbarButtons>
                </Toolbar>

                <PortalContainer>
                    <CustomizationForm
                        ref="form"
                        intl={ intl }
                        data={ this.props.data }
                        onSubmit={ this.handleSave }

                        unit={ unit }
                        unitId={ unitId }
                        />
                </PortalContainer>

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

}


Customization.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)(Customization));
