import React, { Component } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import Chart from 'chart.js';
import moment from 'moment';
import styleIdentifiers from './lineGraph.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {
  data: any[][];
  element: Record<string, any>;
}

export type LineGraphProps = StateProps & DispatchProps & OwnProps;

interface LineGraphState {}

export default class LineGraph extends Component<LineGraphProps, LineGraphState> {
  componentDidMount(): void {
    this.createGraph();
  }

  renderLabels = (): any[][] => {
    const { element, data } = this.props;
    const labels = [];
    if (data) {
      data.map((item): void => {
        labels.push(
          element.labelDateFormat
            ? moment(item[element.label]).format(element.labelDateFormat)
            : item[element.label],
        );
        return labels;
      });
    }
    return labels;
  };

  renderData = (data, value): string[] => {
    const result = [];

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

    return result;
  };

  renderDataSet = (): Record<string, any>[] => {
    const { element, data } = this.props;
    const dataset = [];

    const graphData = element && element.value;

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

    return dataset;
  };

  createGraph = (): void => {
    const { element } = this.props;
    const myChart = new Chart(this.graph, {
      type: 'line',
      data: {
        labels: element.reverseData ? this.renderLabels().reverse() : this.renderLabels(),
        datasets: this.renderDataSet(),
      },
      options: { ...element.options },
    });
  };

  setRef = (node): void => {
    if (node) this.graph = node;
  };

  render(): JSX {
    const { element } = this.props;

    return (
      <div className={styles('LineGraph')}>
        <div className={styles('title')}>
          <TextItem path={element.title} />
        </div>
        <canvas className={styles('graph')} ref={(e): void => this.setRef(e)} />
      </div>
    );
  }
}
