import React from "react";
import ms from "pretty-ms";

class RoundTimer extends React.Component {
  constructor(props) {
    super(props);
    const { seconds } = this.props;
    this.state = {
      running: false,
      remaining: seconds,
    }
  }

  componentDidMount() {
    this.timer = setInterval(() => this.countDown(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  countDown() {
    const { remaining } = this.state;
    
    this.setState({ remaining: remaining - 1 });

    if (remaining <= 0) { 
      const { onTimeout } = this.props;
      clearInterval(this.timer);
      onTimeout();
    }
  }
  
  render() {
    const { remaining } = this.state;
    const { style } = this.props;
    return (
      <div style={{ display: "flex", justifyContent: "center", alignItems: "center", ...style }}>
        {remaining > 0 ? <p>Time: {ms(remaining * 1000)}</p> : <p>Time's up!</p>}
      </div>
    );
  }
}

export default RoundTimer;
