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

import { connect } from 'react-redux';
import { taxReportOptionsAction, taxReportAction, selector } from './redux.js';
import { injectIntl } from 'react-intl';
import validator from 'lib/validator';

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

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

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

import Toast from 'components/Toast';

require("./style.scss");


class TaxReportHeader extends AbstractForm {

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

        let dates = [
            { value: "BILLED_DATE", label: intl.formatMessage({ id: "common.dateType.BILLED_DATE" }) },
            { value: "DUE_DATE", label: intl.formatMessage({ id: "common.dateType.DUE_DATE" }) }
        ];

		return (
			<div>
		        <Toolbar>
		            <ToolbarSection>
		                <DetailTitle 
		                    title={ intl.formatMessage({ id: "report.tax.page.title"}) }
		                    titleIcon={ icons.taxReport }
		                    />
		            </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.renderToggleButtons("dateType", "Date type", dates) */}
			            	{ this.renderDateField("from", "From") }
			            	{ this.renderDateField("to", "To") }

			            	{ this.renderCheckbox("aggregate", "Aggregate") }
			            	{ this.renderField("aggregatedAmount", "Amount", { disabled: !valueOf("aggregate") }) }
			            	<div></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;
    } 
}));


const TaxItems = ({ taxItems, currency, i18n }) => {
	if (!Array.isArray(taxItems)) {
		return null;
	}

	return (
		<div>
			{ taxItems.map(taxItem => {
				return (
					<div key={ taxItem.id } className="list-row bottom-border">
						<div className="row-content row">
							<div className="float-left left pv5">
								<div className="secondary"><b>{ taxItem.subject }</b></div>
								<div className="secondary">{ taxItem.id } | { taxItem.subjectTaxId } | { formatDate(taxItem.date, i18n) } </div>
							</div>
							<div className="float-right right pv5">
								<div className="secondary">
									<b>{ formatMoney(taxItem.base, currency, i18n) }</b>
								</div>
								<div className="secondary">
									{ formatMoney(taxItem.tax, currency, i18n) }
								</div>
							</div>
							<div className="clearfix"/>
						</div>
					</div>							
				);
			}) }
		</div>
	);
}



class TaxReportData extends Component {


	renderTaxType(title, taxType, currency, aggregation, i18n, intl) {

		let content = null;
		if (aggregation) {
			content = (
				<div className="pv10 tax-row-details">
					<div className="tax-item">
						<div className="pv10">
							<div className="main-value">{ formatMoney(taxType.expenses.unaggregated.tax, currency, i18n) }</div>  
							<div className="main-label">{ intl.formatMessage(messages.taxPaidUnaggregated) }</div>	
						</div>

						<div className="pv10">
							<div className="secondary-value">{ formatMoney(taxType.expenses.unaggregated.base, currency, i18n) }</div>  
							<div className="secondary-label">{ intl.formatMessage(messages.baseAmount) }</div>	
						</div>
					</div>					
					<div className="tax-item">
						<div className="pv10">
							<div className="main-value">{ formatMoney(taxType.expenses.aggregated.tax, currency, i18n) }</div>  
							<div className="main-label">{ intl.formatMessage(messages.taxPaidAggregated) }</div>	
						</div>

						<div className="pv10">
							<div className="secondary-value">{ formatMoney(taxType.expenses.aggregated.base, currency, i18n) }</div>  
							<div className="secondary-label">{ intl.formatMessage(messages.baseAmount) }</div>	
						</div>
					</div>					
					<div>
						<div className="pv10">
							<div className="main-value">{ formatMoney(taxType.income.unaggregated.tax, currency, i18n) }</div>  
							<div className="main-label">{ intl.formatMessage(messages.taxReceivedUnaggregated) }</div>	
						</div>

						<div className="pv10">
							<div className="secondary-value">{ formatMoney(taxType.income.unaggregated.base, currency, i18n) }</div>  
							<div className="secondary-label">{ intl.formatMessage(messages.baseAmount) }</div>	
						</div>
					</div>					
					<div>
						<div className="pv10">
							<div className="main-value">{ formatMoney(taxType.income.aggregated.tax, currency, i18n) }</div>  
							<div className="main-label">{ intl.formatMessage(messages.taxReceivedAggregated) }</div>	
						</div>

						<div className="pv10">
							<div className="secondary-value">{ formatMoney(taxType.income.aggregated.base, currency, i18n) }</div>  
							<div className="secondary-label">{ intl.formatMessage(messages.baseAmount) }</div>	
						</div>
					</div>					
					<div>
						<div className="pv10">
							<div className="main-value total-value">{ formatMoney(Math.abs(taxType.total.all.tax), currency, i18n) }</div>  
							<div className="main-label">{ intl.formatMessage(taxType.total.all.tax > 0 ? messages.taxPayable : messages.taxReclaim) }</div>	
						</div>

						<div className="pv10">
							<div className="secondary-value">{ formatMoney(Math.abs(taxType.total.all.base), currency, i18n) }</div>  
							<div className="secondary-label">{ intl.formatMessage(messages.baseAmount) }</div>	
						</div>
					</div>					
				</div>
			);

		} else {
			content = (
				<div className="pv10 tax-row-details">
					<div className="tax-item">
						<div className="pv10">
							<div className="main-value">{ formatMoney(taxType.expenses.all.tax, currency, i18n) }</div>  
							<div className="main-label">{ intl.formatMessage(messages.taxPaid) }</div>	
						</div>

						<div className="pv10">
							<div className="secondary-value">{ formatMoney(taxType.expenses.all.base, currency, i18n) }</div>  
							<div className="secondary-label">{ intl.formatMessage(messages.baseAmount) }</div>	
						</div>
					</div>					
					<div>
						<div className="pv10">
							<div className="main-value">{ formatMoney(taxType.income.all.tax, currency, i18n) }</div>  
							<div className="main-label">{ intl.formatMessage(messages.taxReceived) }</div>	
						</div>

						<div className="pv10">
							<div className="secondary-value">{ formatMoney(taxType.income.all.base, currency, i18n) }</div>  
							<div className="secondary-label">{ intl.formatMessage(messages.baseAmount) }</div>	
						</div>
					</div>					
					<div>
						<div className="pv10">
							<div className="main-value total-value">{ formatMoney(Math.abs(taxType.total.all.tax), currency, i18n) }</div>  
							<div className="main-label">{ intl.formatMessage(taxType.total.all.tax > 0 ? messages.taxPayable : messages.taxReclaim) }</div>	
						</div>

						<div className="pv10">
							<div className="secondary-value">{ formatMoney(Math.abs(taxType.total.all.base), currency, i18n) }</div>  
							<div className="secondary-label">{ intl.formatMessage(messages.baseAmount) }</div>	
						</div>
					</div>					
				</div>
			);
		}

		return (
			<div key={ taxType.name } className="p10 hover-highlight-light">
				<h3>{ title }</h3>
				<div className="pv10">
					{ content }
				</div>
			</div>
		);
	}


	render() {
		let { summary, taxTypes, currencySymbol, intl, i18n } = this.props;

		let types = [];
		if (taxTypes) {
			for (let key in taxTypes) {
				types.push(this.renderTaxType(taxTypes[key].name, taxTypes[key], currencySymbol, this.props.aggregate, i18n, intl));
			}
		}

		return (
			<div>
				{ types }
				{ types.length ? this.renderTaxType(intl.formatMessage(messages.summary), summary, currencySymbol, false, i18n, intl) : null }
			</div>
		);
	}

}

class TaxReport extends Component {

	constructor(props) {
		super(props);

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


	componentWillMount() {
		let unitId = this.props.unitId;
		this.generateReport(this.props.params);
	} 


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

	generateReport(params) {
		let unitId = this.props.unitId;
		this.props.taxReportAction(unitId, params);
	}

	render() {
		let pending = this.props.status === "pending";
		let { intl, i18n, options, params } = this.props;

		return (
			<div className="pv10">
				<TaxReportHeader 
					i18n={ i18n } 
					taxTypes={ options.tax }
					onSubmit={ this.generateReport }
					onBack={ this.handleBack }
					data={ params }
					/>

				<div className="pv10">
					<TaxReportData 
						intl={ intl }
						aggregate={ this.props.params && this.props.params.aggregate }
						{...this.props.data} 
						/>
				</div>
			</div>
		);
	}

}

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



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



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


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