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

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


import { PageTitle, ActivityIndicator, Info, MessagePanel, SummaryPanel, ToolbarButton, Toolbar, ToolbarSection, ToolbarButtons, ToolbarRow, PageSwitcher } from 'lib/components';

//components
import RatingPieChart from 'components/RatingPieChart';
import RatingBarChart from 'components/RatingBarChart';
import CopyrightInfo from 'components/CopyrightInfo';
import FetchedContent, { ErrorInfo } from 'components/FetchedContent';

//localization
import { injectIntl } from 'react-intl';
import { formatMoney, formatDate, formatNumber } from 'lib/i18n';
import { settingsSelector } from 'utils/settings';

import palette from 'utils/palette';
import icons from 'constants/icons';
import messages from './messages.js';
import moment from 'moment';

require("./Home.scss");



//TODO
class DashboardList extends Component {
	render() {
		let { data, fresh, paging, status, i18n, unitId, sorting, from, to, dateType, className, error, onRefresh, intl } = this.props;
		let content = null;

        return (
            <FetchedContent 
                status={ status } 
                className={ className } 
                error={ error } 
                fresh={ fresh } 
                empty={ !data || !data.length } 
                size="big"
                onRefresh={ onRefresh }>

                { Array.isArray(data) ? data.map((row, key) => {
                    let rating = row.rating;
                    let amountClassName = "right main-value p5 ";

                    if (rating > 6) {
                        amountClassName += "plus-amount";
                    } else if (rating > 3) {
                        amountClassName += "neutral-amount";
                    } else {
                        amountClassName += "minus-amount";
                    }

                    let date = moment(row.created).format('DD.MM.YYYY HH:mm:ss');

                    return (
                        <div key={ key } className="flex-list-row">
                            <div className="content">
                                <div className="list-row-data">
                                    <div className="main">
                                        <div className="main-value">
                                            { date }
                                        </div>
                                    </div>
                                    <div className={ amountClassName }>
                                        { rating }
                                    </div>
                                </div>
                            </div>
                        </div>
                    );
                }) : null }

                <PageSwitcher
                    paging={ paging } 
                    displayNoPages
                    onPageChanged={ (paging) => this.props.fetchRatingsAction({ from, to }, paging, sorting) } 
                    status={ status } 
                    disabled={ status == "pending" }
                    /> 
            </FetchedContent>
        );
	}
}

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

DashboardList = connect((state, props) => state.getIn(["home", "list"]).toJS(), (dispatch, props) => {
    return {
        dispatch,
        fetchRatingsAction: (filter, paging, sorting) => dispatch(fetchRatingsAction(filter, paging, sorting))
    };
})(DashboardList);
DashboardList = injectIntl(DashboardList);


class DashboardSummary extends Component {

	renderSummaryPanel(status, title, description, content, intl, className) {
		return (
			<div className="col-md-6 p5">
                { status == "failed" ? <div className={ `summary-panel ${className}` }><ErrorInfo size="micro"/></div> : (
    				<SummaryPanel 
    					className={ className }
    					title={ title ? intl.formatMessage(title) : "" } 
    					content={ content }
    					description={ description }
    					pending={ status == "pending" }
    					/>
                ) }                
			</div>
		);
	}

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

		return (
			<div className="row-flex box-margin-5">
				{ this.renderSummaryPanel(status, messages.ratingsCount, "", data.ratings || 0, intl, "income") }
				{ this.renderSummaryPanel(status, messages.averageRating, "", formatNumber(data.average || 0, i18n, 2), intl, "expenses") }
			</div>
		);	}
}

DashboardSummary = connect(settingsSelector((state, props) => state.getIn(["home", "stats"]).toJS()), (dispatch) => ({}))(DashboardSummary);
DashboardSummary = injectIntl(DashboardSummary);


class DashboardBarChart extends Component {

    render() {
        let { data, status, i18n, intl, className } = this.props;
        if (!data) {
            data = {};
        }
        let values = [];
        for (let i = 1; i < 11; i++) {
            values.push(data && data.values[i] || 0);
        }

        return (
            <div>
                { status == "failed" ? <ErrorInfo /> : <RatingBarChart values={ values } /> } 
                <ActivityIndicator show={ status == "pending" } type="overlay" />            
            </div>
        );  }
}

DashboardBarChart = connect(settingsSelector((state, props) => state.getIn(["home", "stats"]).toJS()), (dispatch) => ({}))(DashboardBarChart);
DashboardBarChart = injectIntl(DashboardBarChart);


class DashboardPieChart extends Component {

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

        return (
            <div>
                { status == "failed" ? <ErrorInfo /> : <RatingPieChart data={ data.values } empty={ !data.ratings } /> } 
                <ActivityIndicator show={ status == "pending" } type="overlay" />            
            </div>
        );  }
}

DashboardPieChart = connect(settingsSelector((state, props) => state.getIn(["home", "stats"]).toJS()), (dispatch) => ({}))(DashboardPieChart);
DashboardPieChart = injectIntl(DashboardPieChart);


class Home extends Component {

	constructor(props) {
		super(props);

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


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

	componentWillMount() {
        this.init();
	}

    init() {
        const { list } = this.props;
        this.changePeriod(this.props.periodParams, list && list.paging);
    }

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

		this.props.fetchStatsAction(from, to, dateType);
        this.props.fetchRatingsAction({ from, to }, paging, sorting);
	}


	render() {
		let { intl, i18n, periodParams = {}, unitId } = this.props;
        let { from, to, dateType } = periodParams;
        let { router } = this.context;

		return (
            <div>
            	{/* top section */}
            	<div className="dashboard-row">
            		<div className="col-xs-12 p10">
                        <Toolbar>
                            <ToolbarSection>
                                <PageTitle title={ intl.formatMessage(messages.pageTitle) } titleIcon={ icons.home } />
                            </ToolbarSection>
                            <ToolbarButtons>
                                <ToolbarButton label={ intl.formatMessage(messages.refreshButton) } onClick={ this.init }>
                                    <span className="icon">{ icons.refresh }</span>
                                </ToolbarButton>
                            </ToolbarButtons>
                        </Toolbar>
            		</div>
            	</div>
            	<div className="dashboard-row">
            		<div className="col-md-4">
            			<div className="p10 min-height-120">
            				<DashboardList from={ from } to={ to } i18n={ i18n } onRefresh={ this.init } />
            			</div>
            		</div>
            		<div className="col-md-8">
                        <div className="p10">
                            <DashboardSummary i18n={ i18n } onRefresh={ this.init }/>
                        </div>
                        <div className="p10">
                            <DashboardBarChart i18n={ i18n } onRefresh={ this.init }/>
                            <DashboardPieChart i18n={ i18n } onRefresh={ this.init }/>
                        </div>
            		</div>
            	</div>

	            <CopyrightInfo version={ global.cfg.version || "0.0.1" }/>
			</div>
		);
	}

}

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



function mapDispatchToProps(dispatch, props) {
	return {
    	fetchStatsAction: (from, to, dateType) => dispatch(fetchStatsAction(from, to, dateType)),
        fetchRatingsAction: (filter, paging, sorting) => dispatch(fetchRatingsAction(filter, {...paging, pageSize: 7}, sorting))
  	};
}


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