import React from 'react';
import styles from '../styles/data_show.less';

class DataShow extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      animatedValues: [],
    };
  }

  componentDidMount() {
    this.startAnimation(this.props.options);
  }

  componentDidUpdate(prevProps) {
    if (prevProps.options !== this.props.options) {
      this.startAnimation(this.props.options);
    }
  }

  startAnimation(data) {
    this.setState({ animatedValues: data.map(() => 0) });

    data.forEach((item, index) => {
      this.animateNumber(item.value, 3000, 0, (val) => {
        this.setState((prevState) => {
          const newValues = [...prevState.animatedValues];
          newValues[index] = val;
          return { animatedValues: newValues };
        });
      });
    });
  }

  animateNumber(target, duration = 2000, decimals = 0, onUpdate) {
    const startTime = performance.now();

    const step = (now) => {
      const progress = Math.min((now - startTime) / duration, 1);
      const current = +(progress * target).toFixed(decimals);
      if (onUpdate) onUpdate(current);

      if (progress < 1) {
        requestAnimationFrame(step);
      } else {
        onUpdate(target);
      }
    };

    requestAnimationFrame(step);
  }

  render() {
    const { options } = this.props;
    const { animatedValues } = this.state;

    return (
      <div className={styles.data_show}>
        {options.map((item, index) => (
          <div className={styles.dataCard} key={index}>
            <div className={styles.data_value}>
              {Number(animatedValues[index] || 0).toLocaleString()}
            </div>
            <div className={styles.data_label}>{item.label}</div>
          </div>
        ))}
      </div>
    );
  }
}

export default DataShow;
