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

import { connect } from 'react-redux';
import { prepareEntity, fetchEntity, saveEntity, deleteEntity, fetchCustomerStats, selector } from './redux.js';
import Toast from 'components/Toast';

import { AbstractForm, DetailButtons, ActivityIndicator, DetailTitle, ToolbarButton, Toolbar, ToolbarSection, ToolbarButtons, Alert, PortalContainer, Tabs, Tab, ErrorBubble, Grid } from 'lib/components';

import icons from 'constants/icons';

import ContactList from 'components/ContactList';
import CustomerStats from 'components/CustomerStats';
import StatusChart from 'components/StatusChart';
import AnnualBarChart from 'components/AnnualBarChart';
import Attachments from 'lib/attachment';
import { PeriodTitle } from 'containers/Params';

import form from 'lib/form';
import validator from 'lib/validator';

import { injectIntl } from 'react-intl';
import messages from './messages.js';
import commonMessages from '../../messages.js';


class CustomerForm extends AbstractForm {

    render() {
        let { intl, edit, customerId, disabled, attachments, className, unitId, errors, onChangePeriod, overview, overviewStatus } = this.props;
        let fieldProps = { disabled: disabled };
        let pending = overviewStatus == "pending";

        return (
            <div className={ className }>

                <Tabs className="mb20">
                    { edit ? 
                        <Tab title={ intl.formatMessage(messages.tabOverview) } className="container-max-1200">
                            <PeriodTitle changePeriod={ onChangePeriod }/>

                            <div className="p10 pv20 mv20 hover-highlight-light relative">
                                <CustomerStats stats={ overview.stats } status={ overviewStatus } currency={ this.props.currency } i18n={ this.props.i18n } />
                                <ActivityIndicator show={ pending } type="overlay" />
                            </div>
                            <Grid container>
                                <Grid item className="p10 pv20 hover-highlight-light relative">
                                    <h3>{ intl.formatMessage(messages.overviewStatusTitle) }</h3>
                                    <StatusChart empty={ !overview.statusData || overview.empty } data={ overview.statusData } currency={ this.props.currency } className="p20"/>
                                    <ActivityIndicator show={ pending } type="overlay" />
                                </Grid>
                                <Grid item className="p10 pv20 hover-highlight-light relative">
                                    <h3>{ intl.formatMessage(messages.overviewAnnualTitle) }</h3>
                                    <AnnualBarChart empty={ !overview.years }  years={ overview.years && overview.years.labels } values={ overview.years && overview.years.values }  className="p20"/>
                                    <ActivityIndicator show={ pending } type="overlay" />
                                </Grid>
                            </Grid>
                           
                        </Tab>
                    : null }
                    <Tab title={ intl.formatMessage(messages.tabCustomer) } titleDecorator={ <ErrorBubble errors={ errors } fields={ ["name"] } /> }>
                        <PortalContainer>
                            <div className="form">
                                { this.renderField("name", intl.formatMessage(messages.name), { ...fieldProps, className: "big", required: true }) }
                                <div className="row-margin-10">
                                    <div className="col-sm-6">
                                        { this.renderField("idNumber", intl.formatMessage(messages.idNumber), fieldProps) }
                                    </div>
                                    <div className="col-sm-6">
                                        { this.renderField("taxNumber", intl.formatMessage(messages.taxNumber), fieldProps) }
                                    </div>
                                </div>
                                { this.renderTextArea("address", intl.formatMessage(messages.address), fieldProps) }
                            </div>
                        </PortalContainer>
                    </Tab>
                    <Tab title={ intl.formatMessage(messages.tabContacts) }>
                        <PortalContainer>
                            <ContactList 
                                items={ this.props.valueOf("contacts") } 
                                onChange={ this.props.onChangeHandler("contacts", items => items) }
                                disabled={ this.props.disabled }
                                />
                        </PortalContainer>
                    </Tab>
                    <Tab title={ intl.formatMessage(messages.tabCustomization) }>
                        <PortalContainer>
                            <div className="form">
                                { this.renderField("invoiceEmail", intl.formatMessage(messages.invoiceEmail), fieldProps) }
                                { this.renderField("invoiceEmailSubject", intl.formatMessage(messages.invoiceEmailSubject), fieldProps) }
                                { this.renderField("invoiceEmailTitle", intl.formatMessage(messages.invoiceEmailTitle), fieldProps) }
                                { this.renderTextArea("invoiceEmailMessage", intl.formatMessage(messages.invoiceEmailMessage), fieldProps) }
                            </div>
                        </PortalContainer>
                    </Tab>
                    <Tab title={ intl.formatMessage(messages.tabAttachments) } disabled={ !edit }>
                        <PortalContainer>
                            { attachments ? (
                                <Attachments 
                                    unitId={ unitId } 
                                    objectType="customer" 
                                    objectId={ customerId }
                                    disabled={ !attachments || disabled }
                                    />
                            ) : null }
                        </PortalContainer>
                    </Tab>
                </Tabs>

            </div>
        );
    }

}



CustomerForm = form(injectIntl(CustomerForm), { 
    onValidationFailed: Toast.validationFailed,
    validate: (customer, error) => {
        let valid = true;
        if (!validator.required(customer.name)) {
            valid = false;
            error({ field: "name", code: commonMessages.validationFieldRequired.id });
        }
        return valid;
    }
});




class CustomerDetail extends Component {

	constructor(props) {
		super(props);

		this.handleBack = this.handleBack.bind(this);
		this.handleDelete = this.handleDelete.bind(this);
		this.handleSave = this.handleSave.bind(this);

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


	componentWillMount() {
		let id = this.props.params.customerId;
		let unitId = this.props.unitId;
        
		if (id) {
			this.props.fetchEntity(unitId, id);
            this.changePeriod(this.props.periodParams);
		} else {
			this.props.prepareEntity();
		}
	}

    async changePeriod(params) {
        let { from, to, dateType } = params || {};
        let id = this.props.params.customerId;
        this.props.fetchCustomerStats(this.props.unitId, { cid: id, from, to, dateType })
    }

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


	async handleSave(data) {
		let id = this.props.params.customerId;
		let intl = this.props.intl;
		try {
			data = await this.props.saveEntity(1, data.id, data);
			Toast.saved();
			if (!id) {
				this.context.router.push(`/customers/${data.value.body.id}`);
			}
		} catch (e) {
            Toast.error(e);
		}
	}


	handleDelete() {
		let intl = this.props.intl;
        Alert.alert(
            intl.formatMessage(messages.deleteTitle), 
            intl.formatMessage(messages.deleteQuestion), 
            [
                { text: intl.formatMessage(commonMessages.buttonNo) }, 
                { text: intl.formatMessage(commonMessages.buttonYes), primary: true, onPress: async () => {
                    try {
                        await this.props.deleteEntity(1, this.props.params.customerId);
                        Toast.deleted();
                        this.context.router.push(`/customers`);
                    } catch (e) {
                        Toast.error(e);
                    }
                }
            }]
        );

	}


	render() {
		let edit = !!this.props.params.customerId;
		let status = this.props.status;
		let pending = !!(status && ( status.isFetching || status.isSaving || status.isDeleting));
		let intl = this.props.intl;

		return (
			<div className="pv10">
                <Toolbar>
                    <ToolbarSection>
						<DetailTitle 
							title={ (this.props.data && this.props.data.name) || intl.formatMessage(messages.title) }
							titleIcon={ icons.customers }
							/>
                    </ToolbarSection>
                    <ToolbarButtons>
                        <ToolbarButton 
                        	label={ intl.formatMessage({ id: "common.button.back" }) } 
                        	onClick={ this.handleBack }>
                            <span className="icon">{ icons.back }</span>
                        </ToolbarButton>
                        { edit ? (
	                        <ToolbarButton 
	                        	label={ intl.formatMessage({ id: "common.button.delete" }) } 
	                        	onClick={ this.handleDelete }>
	                            <span className="icon">{ icons.delete }</span>
	                        </ToolbarButton>
	                    	) : null }
                        <ToolbarButton 
                        	label={ intl.formatMessage({ id: "common.button.save" }) } 
                        	onClick={ () => this.refs.form.submit(this.handleSave) }>
                            <span className="icon">{ icons.save }</span>
                        </ToolbarButton>
                    </ToolbarButtons>
                </Toolbar>

				<CustomerForm 
					ref="form"
                    edit={ edit }
					data={ this.props.data } 
					stats={ this.props.stats }
					currency={ this.props.unit.currencySymbol }

					attachments={ edit }
					unitId={ this.props.unitId }
					customerId={ this.props.params.customerId }

					intl={ this.props.intl }
					disabled={ pending }
                    onChangePeriod={ this.changePeriod }

                    overview={ this.props.overview || {} }
                    overviewStatus={ this.props.overviewStatus || "pending" }

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

}

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



const mapStateToProps = (state, props) => selector(state);



function mapDispatchToProps(dispatch, props) {
	return {
    	dispatch,
    	prepareEntity: () => dispatch(prepareEntity()),
    	fetchEntity: (unitId, id) => dispatch(fetchEntity(id, { unitId })),
    	saveEntity: (unitId, id, data) => dispatch(saveEntity(id, data, { unitId })),
    	deleteEntity: (unitId, id) => dispatch(deleteEntity(id, { unitId })),
    	fetchCustomerStats: (unitId, params) => dispatch(fetchCustomerStats(unitId, params))
  	};
}


export default injectIntl(connect(mapStateToProps, mapDispatchToProps)(CustomerDetail));
