import React from 'react';
import PropTypes from 'prop-types';

import * as charts from 'react-chartjs-2';
import Title from '../Title';

// Style
/* istanbul ignore next */
if (typeof window !== 'undefined') require('./style.scss');

/**
 * Display some `data` as a numeric metric or a chart.
 */
export default class Metric extends React.Component {
  static propTypes = {
    chart: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
    data: PropTypes.oneOfType([PropTypes.object, PropTypes.number, PropTypes.string]).isRequired,
    label: PropTypes.string,
  };

  static defaultProps = {
    label: '',
  };

  chart = () => {
    const chartType = this.props.chart.charAt(0).toUpperCase() + this.props.chart.substring(1);
    return new charts[chartType]();
  };

  render() {
    return (
      <div
        className={['Metric', this.props.className, this.props.chart ? 'Metric_chart' : ''].join(' ')}
        style={this.props.style}
      >
        <div className="Metric-value">
          {this.props.chart ? (
            <this.chart data={this.props.data} options={{ maintainAspectRatio: false, ...this.props.data.options }} />
          ) : (
            <Title className="Metric-label" level={1}>
              {this.props.data}
            </Title>
          )}
        </div>
        {this.props.children || (
          <Title level={5}>
            <b>{this.props.label}</b>
          </Title>
        )}
      </div>
    );
  }
}
