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

require('./style.scss');

export default ({ labels, colors, values, percents, currency, i18n, useChartColors, calculatePercents }) => {
    if (!Array.isArray(labels) || !labels.length) {
        return null;
    }

    if (calculatePercents) {
        percents = [];
        if (Array.isArray(values)) {
            let total = 0;
            values.forEach(v => !isNaN(v) ? total += v : 0);
            if (total) {
                values.forEach(v => percents.push(v / total * 100));    
            }
        }
    }
    let showPercent = Array.isArray(percents) && percents.length;

    if (!Array.isArray(colors)) {
        colors = [];
    }

    if (!Array.isArray(values)) {
        values = [];
    }

    return (
        <div className="doughnut-chart-legend">
            { labels.map((label, idx) => {
                let value = values.length > idx ? values[idx] : 0;
                let color = colors.length > idx ? colors[idx] : "#CECECE";

                let percent = null;
                if (showPercent) {
                    percent = (
                        <div>
                            { formatPercent(percents.length > idx ? percents[idx] : 0, i18n) }
                        </div>
                    );
                }

                return (
                    <div className="legend-row" key={ idx }>
                        <div className="color" style={{ backgroundColor: color }}/>
                        <div className="main-data">
                            <div>
                                { label }
                            </div>
                        </div>
                        <div className="values">
                            <div className="value" style={ useChartColors ? { color: color } : null }>
                                { formatMoney(value, currency, i18n) }
                            </div>
                            { percent }
                        </div>
                    </div>
                );
            }) }
        </div>
    );
}
