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

import { connect } from 'react-redux';
import { fetchList, selector, incomeStatusReportAction, incomeTimelineReportAction, incomeSummaryReportAction } from './redux.js';

//components
//import { FilterForm } from 'lib/components';
import IncomeList from 'components/IncomeList';
import StatusChart from 'components/StatusChart';
import IncomeTimelineChart from 'components/IncomeTimelineChart';
import FetchedContent from 'components/FetchedContent';
import { ActivityIndicator, Button, ButtonBar, PageSwitcher, ListTitle, SectionHeader, ToolbarButton, Toolbar, ToolbarSection, ToolbarButtons, ToolbarRow, LabeledValue } from 'lib/components';

import { injectIntl } from 'react-intl';
import { formatMoney, formatDate } from 'lib/i18n';
import icons from 'constants/icons';
import palette from 'utils/palette';
import { settingsSelector } from 'utils/settings';

import { PeriodTitle } from 'containers/Params';
import CustomerChart from 'components/CustomerChart';
import CustomerStats from 'components/CustomerStats';

import messages from './messages.js';


require("./style.scss");

function renderButtons(intl, router) {
    return [
        <ToolbarButton 
            key="income"
            label={ intl.formatMessage(messages.addIncome) }
            onClick={ () => router.push("/income/new") } 
            >
            <span className="icon">{ icons.add }</span>
        </ToolbarButton>,
        <ToolbarButton 
            key="invoice"
            label={ intl.formatMessage(messages.addInvoice) }
            onClick={ () => router.push("/invoices/new") } 
            >
            <span className="icon">{ icons.add }</span>
        </ToolbarButton>
    ];
}

class DashboardStatusChart extends Component {

    render() {
        let { data, status, i18n, intl, unit } = this.props;

        let 
            draftLabel = intl.formatMessage(messages.draft),
            activeLabel = intl.formatMessage(messages.active),
            finishedLabel = intl.formatMessage(messages.finished),
            overdueLabel = intl.formatMessage(messages.overdue);

        return (
            <div className="pv20 relative">
                { data ? (
                    <div className="hover-highlight-light">
                        <h2>{ intl.formatMessage(messages.statusTitle) }</h2>
                        <StatusChart 
                            data={ data.data } 
                            currency={ data.currencySymbol || data.currency || unit.currencySymbol || unit.currency } 
                            i18n={ i18n } 
                            draftLabel={ draftLabel }
                            activeLabel={ activeLabel }
                            finishedLabel={ finishedLabel }
                            overdueLabel={ overdueLabel }
                            /> 
                    </div> 
                ): null }
                <ActivityIndicator show={ status === "pending" } type="overlay" size="big" />
            </div>
        );  
    }
}

DashboardStatusChart = connect(settingsSelector((state, props) => state.getIn(["incomeList", "statusReport"]).toJS()), () => ({}) )(DashboardStatusChart);
DashboardStatusChart = injectIntl(DashboardStatusChart);


class IncomeSummary extends Component {

    render() {
        let { data, status, i18n, intl } = this.props;
        let { currencySymbol, currency, title, description, pending } = data || {};

        let 
            totalLabel = intl.formatMessage(messages.summaryTotal),
            averageAmount = intl.formatMessage(messages.averageAmount),
            monthlyAverage = intl.formatMessage(messages.monthlyAverage);

        let c = currencySymbol || currency;

        return (
            <div className="pv20 hover-highlight-light relative">
                    { data ? (
                        <div className="center">
                            <LabeledValue label={ totalLabel } size="big">
                                { formatMoney(data.totalIncome, c, i18n) }
                            </LabeledValue>
                            <LabeledValue label={ averageAmount } size="big">
                                { formatMoney(data.averageAmount, c, i18n) }
                            </LabeledValue>
                            <LabeledValue label={ monthlyAverage } size="big">
                                { formatMoney(data.averageMonthlyIncome, c, i18n) }
                            </LabeledValue>
                        </div> 
                    ): null }
                {<ActivityIndicator show={ status === "pending" } type="overlay" size="big" />}
            </div>
        );  
    }
}

IncomeSummary = connect((state, props) => state.getIn(["incomeList", "summaryReport"]).toJS(), () => ({}) )(IncomeSummary);
IncomeSummary = injectIntl(IncomeSummary);


class Income extends Component {


	constructor(props) {
		super(props);

		this.changePeriod = this.changePeriod.bind(this);
	}


	componentWillMount() {
		this.changePeriod(this.props.periodParams, this.props.list.paging, this.props.list.sorting);
	}


	changePeriod(periodParams, paging, sorting) {
		let { from, to, dateType } = periodParams;
		this.props.fetchList(this.props.unitId, { from, to, dateType }, paging, sorting);
		this.props.incomeStatusReportAction(this.props.unitId, { from, to, dateType });
        this.props.incomeTimelineReportAction(this.props.unitId, { from, to, dateType });
        this.props.incomeSummaryReportAction(this.props.unitId, { from, to, dateType });
	}



	render() {
		let { intl, list, timelineReport, i18n } = this.props;
		let content = null;
		let pending = list.status == "pending";

		return (
			<div className="pv10">
                <Toolbar>
                    <ToolbarSection>
						<ListTitle 
							title={ intl.formatMessage(messages.title) }
							titleIcon={ icons.incomePortal }
							/>
                    </ToolbarSection>
                    <ToolbarButtons>
                        { renderButtons(intl, this.context.router) }
                    </ToolbarButtons>
                    <ToolbarRow>
		                <PeriodTitle
		                	size="normal"
		                	changePeriod={ this.changePeriod }
		                	/>
                    </ToolbarRow>
                </Toolbar>

                <div className="dashboard-row">
                    <div className="col-md-6 p10">
                        <FetchedContent 
                            status={ list.status } 
                            error={ list.error } 
                            fresh={ list.fresh } 
                            empty={ !list.data || !list.data.length } 
                            buttons={ renderButtons(intl, this.context.router) }>

                            <IncomeList 
                                items={ list.data } 
                                onDetailClick={ (id, row) => {
                                        if (row.incomeType == "income") {
                                            this.context.router.push(`/income/${id}`)   
                                        } else {
                                            this.context.router.push(`/invoices/${id}`) 
                                        }
                                    } 
                                }
                                i18n={ this.props.i18n }
                                disabled={ pending }
                                />
                            { list.data ? 
                                <PageSwitcher 
                                    paging={ list.paging } 
                                    onPageChanged={ (paging) => this.props.fetchList(this.props.unitId, list.filter, paging, list.sorting) } 
                                    status={ list.status } 
                                    disabled={ pending }
                                    /> : null 
                            }

                        </FetchedContent>
                    </div>
                    <div className="col-md-6 p10">
                    	<div className="mv20">
                            <div className="status-charts">
                                <DashboardStatusChart i18n={ i18n }/>
                                <IncomeSummary i18n={ i18n }/>
                            </div>
                            <div className="hover-highlight-light p10 relative">
                                <h2>{ intl.formatMessage(messages.timelineTitle) }</h2>
                                <div className="pv20">
                                    { timelineReport ? <IncomeTimelineChart { ...timelineReport.data } status={ timelineReport.status } /> : null }
                                    <ActivityIndicator show={ timelineReport && timelineReport.status === "pending" } type="overlay" size="big" />
                                </div>
                            </div>
                    	</div>
                    </div>
                </div>


			</div>
		);
	}

}

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



const mapStateToProps = selector;


function mapDispatchToProps(dispatch, props) {
	return {
    	dispatch,
		fetchList: (unitId, filter, paging, sorting) => dispatch(fetchList(filter, paging, sorting, { unitId })),
		incomeStatusReportAction: (unitId, params) => dispatch(incomeStatusReportAction(unitId, params)),
        incomeTimelineReportAction: (unitId, params) => dispatch(incomeTimelineReportAction(unitId, params)),
        incomeSummaryReportAction: (unitId, params) => dispatch(incomeSummaryReportAction(unitId, params)),
  	};
}


export default injectIntl(connect(selector, mapDispatchToProps)(Income));
