import React, { Component } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import { config, stats } from 'config/general';
import LineGraph from 'components/items/LineGraph';
import CountUp from 'react-countup';
import CustomIcon from 'components/items/CustomIcon';
import BarGraph from 'components/items/BarGraph';
import styleIdentifiers from './stats.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type StatsProps = StateProps & DispatchProps & OwnProps;

interface StatsState {}

const SimpleValue = ({ element, data }): JSX => (
  <div className={styles('card')}>
    <div className={styles('title')}>{element.title}</div>
    <div className={styles('background')}>
      {data[element.value] ? (
        <CountUp className={styles('result')} duration={1} end={data[element.value]} />
      ) : (
        <div className={styles('result')}>0</div>
      )}
    </div>
  </div>
);

export default class Stats extends Component<StatsProps, StatsState> {
  componentDidMount(): void {
    const { getAll } = this.props;
    getAll();
  }

  renderItem = (element: Record<string, any>, data: any, key: number): JSX => {
    switch (element.type) {
      case 'number':
        return <SimpleValue element={element} data={data} key={key} />;
      case 'line':
        return <LineGraph element={element} data={data} key={key} />;
      case 'bar':
        return <BarGraph element={element} data={data} key={key} />;
      default:
        return false;
    }
  };

  renderSection = (element: Record<string, any>, index): JSX => {
    const { statistics } = this.props;
    const name = element.name || element.resource || element.api;
    let loading = true;
    if (name && statistics[name]) {
      loading = statistics[name].loading;
      if (element.stats && !loading) {
        return (
          <div className={styles('section')} key={index}>
            {element.stats.map(
              (item, key): JSX => this.renderItem(item, statistics[name].data || null, key),
            )}
          </div>
        );
      }
    }
    return false;
  };

  render(): JSX {
    const { refreshAll } = this.props;
    if (!stats) return false;

    return (
      <div className={styles('Stats')}>
        {config.refreshAllStats && (
          <div className={styles('refresh')} onClick={refreshAll}>
            <CustomIcon icon="sync-alt" />
          </div>
        )}
        {stats.map((item, index): JSX => this.renderSection(item, index))}
      </div>
    );
  }
}
