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

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

import PaymentItemForm from 'components/PaymentItemForm';
import RecurringPaymentItemForm from 'components/RecurringPaymentItemForm';
import { ActivityIndicator, DetailButtons, DetailTitle, ToolbarButton, Toolbar, ToolbarSection, ToolbarButtons, Alert } from 'lib/components';

import { periodCheckDecorator } from 'containers/Params';
import { formatDate } from 'lib/i18n'

import Toast from 'components/Toast';
import { injectIntl } from 'react-intl';
import messages from './messages.js';
import commonMessages from '../../messages.js';
import icons from 'constants/icons';


class PaymentDetail extends Component {

	constructor(props) {
		super(props);

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


	componentWillMount() {
		let id = this.props.params.paymentId;
		let unitId = this.props.unitId;
		if (id) {
			this.props.fetchEntity(unitId, id);
		} else {
			this.props.prepareEntity(this.props.unit, this.props.params.mode, this.props.params.categoryId);
		}
	} 


	handleBack() {
        let { onBack, backPath, route } = this.props;
        if (typeof onBack === "function") {
            return onBack();
        }
        if (backPath) {
            return this.context.router.push(backPath);
        }
        if (route && route.backRoute) {
            return this.context.router.push(route.backRoute);
        }

		let { categoryId } = this.props.params;
		if (categoryId) {
			this.context.router.push(`/payments/categories/${categoryId}`);
		} else {
			this.context.router.push('/payments');	
		}
		
	}


    handleSave(data) {
        let { periodParams, intl, route } = this.props;
        periodCheckDecorator(async () => {
            let id = this.props.params.paymentId;
            let type = this.props.params.mode;
            let unitId = this.props.unitId;

            try {
                data = await this.props.saveEntity(unitId, data.id, data, { type });
                Toast.saved();
                if (!id) {
                    if (type == "rec") {
                        this.context.router.push(`/payments`);
                    } else {
                        if (route && route.successRoute) {
                            this.context.router.push(`${route.successRoute}/${data.value.body.id}`);
                        } else {
                            this.context.router.push(`/payments/${data.value.body.id}`);
                        }
                    }
                }
            } catch (e) {
                Toast.error(e);
            }
        }, {
            periodParams,
            date: data.dueDate,
            title: intl.formatMessage({ id: "payment.dateAlert.title" }),
            text: intl.formatMessage({ id: "payment.dateAlert.text" }, { date: formatDate(data.dueDate), dateFrom: formatDate(periodParams.from), dateTo: formatDate(periodParams.to) }),
            yesLabel: intl.formatMessage({ id: "common.button.yes" }),
            noLabel: intl.formatMessage({ id: "common.button.no" })
        });
    }


    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(this.props.unitId, this.props.params.paymentId);
                        this.handleBack();
                        Toast.deleted();
                    } catch (e) {
                        Toast.error(e);
                    }
                }
            }]
        );
    }


	render() {
		let 
			intl = this.props.intl,
			id = this.props.params.paymentId,
			mode = this.props.params.mode,
			status = this.props.status || {},
			unitId = this.props.unitId,
            unit = this.props.unit,
            i18n = this.props.i18n,
			edit = !!id,
			form = null;


		if (!edit && mode == "rec") {
			form = <RecurringPaymentItemForm 
                ref="detailForm" 
                data={ this.props.data } 
                disabled={ status.any } 
                onSubmit={ this.handleSave } 
                unitId={ unitId } 
                i18n={ i18n }
                paymentReadOnly={ !!this.props.params.categoryId }
                />
		} else {
			form = (
                <PaymentItemForm 
                    ref="detailForm" 
                    data={ this.props.data } 
                    disabled={ status.any } 
                    onSubmit={ this.handleSave } 
                    unitId={ unitId }
                    unit={ unit }
                    i18n={ i18n }
                    paymentReadOnly={ !!this.props.params.categoryId }
                    />

            );
		}

		return (
			<div className="pv10">
                <Toolbar>
                    <ToolbarSection>
                        <DetailTitle 
                            title={ (this.props.data && this.props.data.name) || intl.formatMessage(mode == "rec" ? messages.recurringTitle : messages.title) }
                            titleIcon={ icons.payments }
                            />
                    </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.delete" }) } 
                            onClick={ this.handleDelete }
                            disabled={ !edit }>
                            <span className="icon">{ icons.delete }</span>
                        </ToolbarButton>
                        <ToolbarButton 
                            label={ intl.formatMessage({ id: "common.button.save" }) } 
                            onClick={ () => this.refs.detailForm.submit(this.handleSave) }>
                            <span className="icon">{ icons.save }</span>
                        </ToolbarButton>
                    </ToolbarButtons>
                </Toolbar>

                <div className="container-max-900">
    				{ form }
    				<ActivityIndicator show={ status.any } type="overlay" />
                </div>
			</div>
		);
	}

}

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



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



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


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