import React, { useState, useEffect, useRef } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import Chart from 'chart.js';
import styleIdentifiers from './pieGraph.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type PieGraphProps = StateProps & DispatchProps & OwnProps;

const PieGraph = (props: PieGraphProps) => {
  const { element, data, options } = props;
  const graph = useRef(null);

  function dynamicColors() {
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);
    return `rgb(${r},${g},${b})`;
  }

  function renderData(variable) {
    const values = [];

    data.map(item => {
      if (item[variable]) values.push(item[variable]);
      else if (!item[variable] && variable === 'color') values.push(dynamicColors());
    });

    return values;
  }

  function renderLabel() {
    const labels = [];

    data.map(item => {
      labels.push(item.label);
    });

    return labels;
  }

  function renderDataset() {
    const datasets = [];

    datasets.push({
      data: renderData('value'),
      backgroundColor: renderData('color'),
    });

    return datasets;
  }

  function createGraph() {
    const myPieChart = new Chart(graph.current, {
      type: 'pie',
      data: {
        datasets: renderDataset(),
        labels: renderLabel(),
      },
      options: element ? { ...element.options } : options,
    });
  }

  useEffect(() => createGraph(), []);

  return (
    <div className={styles('PieGraph')}>
      <canvas className={styles('graph')} ref={graph} />
    </div>
  );
};

export default PieGraph;
