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

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

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

import form from 'lib/form';

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

import { Line, Bar, HorizontalBar } from 'react-chartjs-2';

import { formatDate, formatMoney, formatNumber } from 'lib/i18n'
import { num } from 'utils/calc'

import './style.scss';

const colors = ["#f79239", "#4ec3e0", "#1287ed", "#929ba3", "#678096", "#5beeff"]; //FIXME!!!



class SummaryReportData extends Component {


    colors(summary) {
        return {
            borderColor: summary,
            backgroundColor: summary,
            pointBorderColor: summary,
            pointBackgroundColor: summary,
            pointHoverBackgroundColor: summary,
            pointHoverBorderColor: summary,
        };
    }

    renderChart(title, currency, data, i18n, intl) {
        let labels = data.labels.slice();
        /*
        for (let i = 0; i <labels.length; i++) {
            labels[i] = formatDate(labels[i]);
        }
        */

        let chart = {
            labels: data.labels,
            datasets: [{
                label: 'Summary',
                type:'line',
                lineTension: 0,
                data: data.summary,
                fill: false,
                yAxisID: 'y-axis-2',
                ...this.colors(colors[0])
            }, {
                type: 'bar',
                label: 'Income',
                data: data.income,
                fill: false,
                yAxisID: 'y-axis-1',
                ...this.colors(colors[1])
            }, {
                type: 'bar',
                label: 'Expenses',
                data: data.expenses,
                fill: false,
                yAxisID: 'y-axis-1',
                ...this.colors(colors[2])
            }, {
                type: 'bar',
                label: 'Payments',
                data: data.payments,
                fill: false,
                yAxisID: 'y-axis-1',
                ...this.colors(colors[3])
            }]
        };

        let options = {
            responsive: true,
            animation: false,
            maintainAspectRatio: false,
            barValueSpacing: 10,
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        return formatMoney(tooltipItem.yLabel, currency);
                    }               
                }
            },
                elements: {
                line: {
                    fill: false
                }
                },
                scales: {
                xAxes: [
                  {
                    display: true,
                    gridLines: {
                      display: false
                    },
                    labels: {
                      show: true
                    },
                    gridLines: {
                        offsetGridLines: true
                    }
                  }
                ],
                yAxes: [
                  {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    id: 'y-axis-1',
                    gridLines: {
                      display: false
                    },
                    labels: {
                      show: true
                    },
                    ticks: {
                        beginAtZero: false,
                        scaleBeginAtZero: false,
                        callback: function(label, index, labels) {
                            return formatNumber(label);
                        }
                    }
                  },
                  {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    id: 'y-axis-2',
                    gridLines: {
                      display: true
                    },
                    labels: {
                      show: true
                    },
                    ticks: {
                        beginAtZero: false,
                        scaleBeginAtZero: false,
                        callback: function(label, index, labels) {
                            return formatNumber(label);
                        }
                    }
                  }
                ]
            }
        };

        return (
            <div className="margin-20">
                <Bar data={ chart } options={ options } height={ 300 }  />
            </div>
        );
    }

    renderSummaryRow(label, income, expenses, payments, summary, avg, currency, i18n, intl, key) {
        if (!avg) {
            avg = 1;
        }

        let avgLabel = intl.formatMessage(messages.monthAverage);

        return (
            <div className="pv10 summary-report-data" key={ key }>
                <div className={ key == -1 ? "box p10" : "p10 hover-highlight-light" }>
                    <h3>{label}</h3>
                    <div className="row row-margin-10">
                        <div className="col-xs-6 col-sm-3 p10 summary-panel">
                            <LabeledValue label={ intl.formatMessage(messages.summaryIncome) }>
                                { formatMoney(income, currency, i18n) }
                            </LabeledValue>
                            <LabeledValue label={ avgLabel } className="secondary">
                                { formatMoney(income / avg, currency, i18n) }
                            </LabeledValue>
                        </div>
                        <div className="col-xs-6 col-sm-3 p10 summary-panel">
                            <div className="summary-row main">
                                <div className="value">{ formatMoney(expenses, currency, i18n) }</div>  
                                <div className="label">{ intl.formatMessage(messages.summaryExpenses)}</div>   
                            </div>
                            <div className="summary-row secondary">
                                <div className="value">{ formatMoney(expenses / avg, currency, i18n) }</div>  
                                <div className="label">{ avgLabel }</div>   
                            </div>
                        </div>
                        <div className="col-xs-6 col-sm-3 p10 summary-panel">
                            <div className="summary-row main">
                                <div className="value">{ formatMoney(payments, currency, i18n) }</div>  
                                <div className="label">{ intl.formatMessage(messages.summaryPayments)}</div>   
                            </div>
                            <div className="summary-row secondary">
                                <div className="value">{ formatMoney(payments / avg, currency, i18n) }</div>  
                                <div className="label">{ avgLabel }</div>   
                            </div>
                        </div>
                        <div className="col-xs-6 col-sm-3 p10 summary-panel">
                            <LabeledValue label={ intl.formatMessage(messages.summarySummary) } size="big">
                                { formatMoney(summary, currency, i18n) }
                            </LabeledValue>
                            <div className="summary-row secondary">
                                <div className="value">{ formatMoney(summary / avg, currency, i18n) }</div>  
                                <div className="label">{ avgLabel }</div>   
                            </div>
                        </div>
                    </div>
                </div>
            </div>              
        );
    }


    renderSummary(data, currency, i18n, intl) {
        let output = [];
        let income = 0, expenses = 0, payments = 0, summary = 0, units = 0;
        for (let i = data.labels.length - 1; i > -1; i--) {
            income += num(data.income[i]);
            expenses += num(data.expenses[i]);
            payments += num(data.payments[i]);
            summary += num(data.summary[i]);
            units += 12;
            output.push(this.renderSummaryRow(data.labels[i], data.income[i], data.expenses[i], data.payments[i], data.summary[i], 12, currency, i18n, intl, i));
        }

        output.unshift(this.renderSummaryRow(data.labels[0] + " - " + data.labels[data.labels.length - 1], income, expenses, payments, summary, units, currency, i18n, intl, -1));

        return output;
    }


    render() {
        let { data, i18n, currency, intl } = this.props;
        if (!(data && data.labels && data.labels.length)) {
            return null;//TODO
        }

        return (
            <div>
                <div>
                    { this.renderChart("", currency, data, i18n, intl) }
                </div>
                <div className="container-max-900">
                    { this.renderSummary(data, currency, i18n, intl) }
                </div>
            </div>
        );
    }

}


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.summaryReport }
                            />
                    </ToolbarSection>
                    <ToolbarButtons>
                        <ToolbarButton 
                            label={ intl.formatMessage(commonMessages.buttonBack) } 
                            onClick={ onBack }>
                            <span className="icon">{ icons.back }</span>
                        </ToolbarButton>
                        <ToolbarButton 
                            label={ intl.formatMessage(commonMessages.buttonSubmit) } 
                            onClick={ () => submit(onSubmit) }>
                            <span className="icon">{ icons.ok }</span>
                        </ToolbarButton>
                    </ToolbarButtons>
                    <ToolbarRow>
                        <div className="form form-material inline-flex-form-even">
                            { this.renderField("period", intl.formatMessage(messages.years)) }
                            <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 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;
    } 
}));


class SummaryReport 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(periodParams) {
        let unitId = this.props.unitId;
        let { period } = periodParams;
        this.props.summaryReportAction(unitId, { period });
    }

    render() {
        let intl = this.props.intl;

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

                <div className="pv10">
                    { this.props.data ? (
                        <SummaryReportData
                            data={ this.props.data } 
                            currency={ this.props.data.currencySymbol }
                            intl={ intl }
                            /> 
                        ) : null }
                </div>
            </div>
        );
    }

}

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



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



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


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