import React, { Component } from 'react';
import { Doughnut } from 'react-chartjs-2';

import { formatMoney, formatDate, formatPercent, formatNumber } from 'lib/i18n';

let options = {
    legend: {
        display: false 
    },
    animate: false,
    animation: {
        animateScale: false,
        animateRotate: false,
    },    
    
};


function renderTooltip(i18n, labels, currency, empty) {
    if (empty) {
        return () => {
            return formatMoney(0, currency, i18n);
        };
    }
    return (tooltipItem, data) => {
        let dataset = data.datasets[tooltipItem.datasetIndex];
        let total = dataset.data.reduce(function(previousValue, currentValue, currentIndex, array) {
            return previousValue + currentValue;
        });
        let currentValue = dataset.data[tooltipItem.index];
        return formatMoney(currentValue, currency, i18n) + " (" + formatPercent(currentValue / total * 100, i18n) + ")";
    }
}

export default ({ stats, colors, currency }) =>  {
    if (!stats) {
        return null;
    }

    let sums = [];
    let labels = [];
    let s = null;
    let empty = !(Array.isArray(stats) && stats.length);
    if (!empty) {
        for (let i = 0; i < stats.length; i++) {
            s = stats[i];
            labels.push(s.customerName);
            sums.push(s.stats.total);
        }
    } else {
        labels.push("");
        sums.push(1);
        colors = ["#DEDEDE"];
    }

    let data = {
        labels: labels,
        datasets: [{
            data: sums,
            backgroundColor: colors
        }]
    };


    return (
        <div className="row row-margin-10">
            <div className="col-md-6 p10">
                <Doughnut data={data} options={ {...options, tooltips: { callbacks: { label: renderTooltip(i18n, labels, currency, empty) }} } } redraw={ true } />
            </div>
            <div className="col-md-6 p5">
                { labels.map((label, i) => <div key={ i } className="p5" style={{ lineHeight: "20px", verticalAlign: "middle"}}><div style={ { display: "inline-block", width: "20px", height: "20px", marginRight: "5px", backgroundColor: colors[i] }}></div>{ label }</div>) }
            </div>
        </div>
    );
    
}
