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

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type BarGraphProps = StateProps & DispatchProps & OwnProps;

const BarGraph = (props: BarGraphProps) => {
  const { element, data } = props;

  const GraphElement = useRef(null);

  function renderLabels() {
    const labels = [];
    let datas = _.cloneDeep(data);

    if (element.length) {
      datas = datas.slice(0, element.length);
    }

    if (datas) {
      datas.map((item): void => {
        labels.push(
          element.labelDateFormat
            ? moment(item[element.label]).format(element.labelDateFormat)
            : item[element.label],
        );
        return labels;
      });
    }
    return labels;
  }

  function renderData(res, value) {
    const result = [];
    let datas = _.cloneDeep(res);

    if (element.treatElement && typeof element.treatElement === 'function') {
      for (let index = 0; index < datas.length; index++) {
        const el = datas[index];
        datas[index] = element.treatElement(el, datas[index + 1]);
      }
    }

    if (element.length) datas = datas.slice(0, element.length);

    if (datas) datas.map((item): void => result.push(item[value]));

    return result;
  }

  function renderDataSet() {
    const dataset = [];

    const graphData = element && element.value;

    if (graphData) {
      graphData.map((item): void =>
        dataset.push({
          data: element.reverseData
            ? renderData(data, item.value).reverse()
            : renderData(data, item.value),
          label: item.label || item.value,
          borderColor: item.color,
          backgroundColor: item.color,
          borderWidth: 2,
          fill: false,
          ...item,
        }),
      );
    }

    return dataset;
  }

  function createGraph() {
    const myChart = new Chart(GraphElement.current, {
      type: 'bar',
      data: {
        labels: element.reverseData ? renderLabels().reverse() : renderLabels(),
        datasets: renderDataSet(),
      },
      options: { ...element.options },
    });
  }

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

  return (
    <div className={styles('BarGraph')}>
      <div className={styles('title')}>
        <TextItem path={element.title} />
      </div>
      <canvas className={styles('graph')} ref={GraphElement} />
    </div>
  );
};

export default BarGraph;
