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

import { connect } from 'react-redux';
import { customerReportAction, selector } from './redux.js';

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


import { injectIntl } from 'react-intl';
import palette from 'utils/palette';

import icons from 'constants/icons';

import form from 'lib/form';


class CustomerReportHeader 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 className="pv10">
		        <Toolbar>
		            <ToolbarSection>
		                <DetailTitle 
		                    title={ intl.formatMessage({ id: "report.customer.page.title" }) }
		                    titleIcon={ icons.customerReport }
		                    />
		            </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", "From") }
			            	{ this.renderDateField("to", "To") }
			            	<div className="inline-form-field-separator"></div>
			            	<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>
		);
	}

}

CustomerReportHeader = injectIntl(form(CustomerReportHeader, {

	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;
    } 
}));


class CustomerReport extends Component {

	constructor(props) {
		super(props);

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


	componentWillMount() {
		this.generateReport(this.props.params);
	} 


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

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



	renderCustomers(data, currency, colors) {
		if (!data) {
			return null;
		}

		return data.map((s, key) => (
			<div key={ key } className="pv10">
				<div className="p20 hover-highlight-light">
					<h3>
						<div style={ { display: "inline-block", width: "20px", height: "20px", marginRight: "5px", backgroundColor: colors[key] }}></div>
						{ s.customerName }
					</h3>
					<CustomerStats key={ key } stats={ s.stats } currency={ currency } />
				</div>
			</div>
		));
	}


	render() {
		let intl = this.props.intl;
		let pending = this.props.status === "pending";
		let colors = [];
		let data = this.props.data;
		let i18n = this.props;

		let currency = null;
		if (data && data.data && data.data.length) {
			colors = palette(global._chartColors, data.data.length);
			currency = data.currencySymbol || data.currency;
		}


		return (
			<div>
				<CustomerReportHeader
					data={ this.props.params } 
					pending={ pending }
					onSubmit={ this.generateReport }
					onBack={ this.handleBack }
					i18n={ i18n }
					/>
				<div className="container-max-900">
					{
						data && data.data ? <CustomerChart stats={ data.data } currency={ currency } colors={ colors } /> : null
					}
					{
						data && data.data ? this.renderCustomers(data.data, currency, colors) : null
					}
				</div>
			</div>
		);
	}

}

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



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



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


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