/* eslint react/destructuring-assignment: off */
import React, {Component} from 'react';
import PropTypes from 'prop-types';

class Countdown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      runCountdown: this.props.runCountdown,
      timer: this.props.time,
    };
    this.interval = null;

    if (this.state.runCountdown) {
      this.startCountdown();
    }
  }

  // eslint-disable-next-line react/no-deprecated
  componentWillReceiveProps(nextProps) {
    this.setState({
      ...nextProps,
    });

    if (nextProps.runCountdown && !this.interval) {
      this.startCountdown();
    } else if (!nextProps.runCountdown && this.interval) {
      this.clearCountdown();
    }
  }

  componentWillUnmount() {
    this.clearCountdown();
  }

  static getFormattedTime(seconds) {
    const s = seconds % 60;
    const fullMinuteQuantity = Math.floor((seconds - s) / 60);
    const m = fullMinuteQuantity ? fullMinuteQuantity % 60 : fullMinuteQuantity;
    const h = Math.floor((seconds - m * 60 - s) / 3600);

    return `${h}:${m}:${s}`;
  }

  startCountdown() {
    let iteration = 1;

    this.interval = window.setInterval(() => {
      if (iteration === this.props.time) {
        window.clearInterval(this.interval);
        this.interval = null;
        this.props.doneCallback();
      } else {
        this.setState({
          timer: this.props.isFormatted
            ? this.props.time - this.props.interval * iteration : this.props.time - iteration,
        });
      }
      iteration += 1;
    }, this.props.interval * 1000);
  }

  clearCountdown() {
    window.clearInterval(this.interval);
    this.interval = null;
  }

  render() {
    if (!this.state.runCountdown) {
      return null;
    }

    const {isFormatted} = this.props;
    const {timer} = this.state;
    const value = isFormatted ? Countdown.getFormattedTime(timer) : timer;

    return (
      <span>{value}</span>
    );
  }
}

Countdown.propTypes = {
  doneCallback: PropTypes.func,
  interval: PropTypes.number,
  runCountdown: PropTypes.bool,
  time: PropTypes.number.isRequired,
  isFormatted: PropTypes.bool,
};

Countdown.defaultProps = {
  doneCallback: null,
  interval: 1,
  runCountdown: false,
  isFormatted: false,
};

export default Countdown;
