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

import { connect } from 'react-redux';
import { cashflowReportAction, selector } from './redux.js';
import { injectIntl } from 'react-intl';
import form from 'lib/form';

import CashflowChart from 'components/CashflowChart';
import { AbstractForm, ActivityIndicator, Button, ButtonBar, DetailTitle, ToolbarButton, Toolbar, ToolbarSection, ToolbarButtons, ToolbarRow } from 'lib/components';
import Toast from 'components/Toast';

import { PeriodTitle, getPeriodParams } from 'containers/Params';
import { formatMoney, formatDate } from 'lib/i18n';


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




class TaxReportHeader extends AbstractForm {

    render() {
        let { intl, onBack, submit, pending, i18n, params, status, onSubmit } = this.props;

        return (
            <div className="pv10">
                <Toolbar>
                    <ToolbarSection>
                        <DetailTitle 
                            title={ intl.formatMessage(messages.title) }
                            titleIcon={ icons.cashflowReport }
                            />
                    </ToolbarSection>
                    <ToolbarButtons>
                        <ToolbarButton 
                            label={ intl.formatMessage({ id: "common.button.back" }) } 
                            onClick={ onBack }>
                            <span className="icon">{ icons.back }</span>
                        </ToolbarButton>
                        <ToolbarButton 
                            label={ intl.formatMessage({ id: "common.button.refresh" }) } 
                            onClick={ () => submit(onSubmit) }>
                            <span className="icon">{ icons.refresh }</span>
                        </ToolbarButton>
                    </ToolbarButtons>
                    <ToolbarRow>
                        <div className="form form-material inline-flex-form-even">
                            { this.renderDateField("from", intl.formatMessage(messages.from)) }
                            { this.renderDateField("to", intl.formatMessage(messages.to)) }
                            { this.renderNumericField("amount", intl.formatMessage(messages.initialAmount)) }
                            <div className="inline-form-field-separator"></div>
                            <div className="inline-form-field-separator"></div>
                            <div className="inline-form-field-separator"></div>
                        </div>
                    </ToolbarRow>
                </Toolbar>
            </div>
        );
    }

}

TaxReportHeader = injectIntl(form(TaxReportHeader, {

    onValidationFailed: Toast.validationFailed,
    validate: (filter, error) => {
        let valid = true;

        /*
        if (!validator.required(filter.from)) {
            valid = false;
            error({ field: "from", code: "common.validation.requiredField" });
        }
        if (!validator.required(filter.to)) {
            valid = false;
            error({ field: "to", code: "common.validation.requiredField" });
        }
        */
        
        return valid;
    } 
}));


function formatAmount(amount, currency, i18n, multiplier = 1) {
    amount = amount * multiplier;
    let amountClassName = "right main-value p5 " + (amount < 0 ? "minus-amount" : "plus-amount");
    return (
        <div className={ amountClassName }>
            <div>
                { formatMoney(amount, currency, i18n) }
            </div>
        </div>
    );
}


class CashflowReport extends Component {

	constructor(props) {
		super(props);

		this.generateReport = this.generateReport.bind(this);
		this.handleBack = this.handleBack.bind(this);
	}


	componentWillMount() {
		let unitId = this.props.unitId;
		let { from, to, dateType } = this.props.params;
		this.props.cashflowReportAction(unitId, { from, to, dateType });
	} 


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

	generateReport(params) {
		let unitId = this.props.unitId;
		let { from, to, dateType } = params;
		this.props.cashflowReportAction(unitId, { from, to, dateType });
	}

	render() {
		let pending = this.props.status === "pending";
		let { intl, params, data } = this.props;
        let { from, to, dateType } = params;

        if (!data) {
            data = {};
        }

		return (
			<div>
                <TaxReportHeader 
                    onSubmit={ this.generateReport }
                    onBack={ this.handleBack }
                    i18n={ this.props.i18n }
                    data={ this.props.params }
                    />

				<div className="pv10">
                    <div style={ { maxHeight: 350 } }>
    					<CashflowChart
    						{...this.props.data} 
    						/>
    
                        <ActivityIndicator show={ pending } type="overlay"/>
                    </div>

                    <div className="pv20 container-max-900">
                        { data && data.data && Array.isArray(data.data.records) ? data.data.records.map((row, key) => {
                            return (
                                <div key={ key } className="flex-list-row">
                                    <div className="content">
                                        <div className="list-row-data">
                                            <div className="record-type">
                                                <div className="icon">
                                                    { icons[row.type] || icons.empty }
                                                    <div className={`status-indicator ${row.status || "pending"}`}/>
                                                </div>
                                                <div className="date">{ formatDate(row.date, i18n) }</div>
                                            </div>
                                            <div className="main">
                                                <div className="main-value">
                                                    { row.name }
                                                </div>
                                                <div className="additional-info">
                                                    { row.description || " " }
                                                </div>
                                            </div>
                                            { formatAmount(row.amount, data.currencySymbol, i18n, row.type == 'income' || row.type == 'invoice' ? 1 : -1) }
                                            { formatAmount(row.balance, data.currencySymbol, i18n) }
                                        </div>
                                    </div>
                                    <div className="actions">
                                        <button className="icon" onClick={ () => handleBillableClick(row.type, row.objectId, router) }>{icons.leftMenu}</button>
                                    </div>
                                </div>
                            )
                        }) : null }
    
                        <ActivityIndicator show={ pending } type="overlay"/>
                    </div>

				</div>
			</div>
		);
	}

}

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



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



function mapDispatchToProps(dispatch, props) {
	return {
    	dispatch,
    	cashflowReportAction: (unit, params) => dispatch(cashflowReportAction(unit, params))
  	};
}


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