import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import Countdown from './Countdown';
import Header from './Header';
import ProgressCircle from './ProgressCircle';
import getUpcomingDate from './getUpcomingDate';

import style from './App.sass';

class App extends React.Component {
  static propTypes = {
    getNow: PropTypes.func,
    weekdays: PropTypes.arrayOf(PropTypes.string),
  }

  static defaultProps = {
    getNow: () => moment(),
    weekdays: [
      'tuesday',
      'thursday',
      'saturday',
    ],
  }

  componentDidMount() {
    this.interval = setInterval(this.updateUpcomingDate.bind(this), 1000);
    this.updateUpcomingDate();
  }

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

  calculateUpcomingDate() {
    const { getNow, weekdays } = this.props;
    const now = getNow();
    return moment.min(
      ...weekdays.map(weekday => getUpcomingDate(now, weekday)),
    );
  }

  updateUpcomingDate() {
    this.setState({ nextUpcomingDate: this.calculateUpcomingDate() });
  }

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

    const { nextUpcomingDate } = this.state;

    return (
      <div className={style.app}>
        <Header>
          VIzon countdown
        </Header>

        <div className={style.content}>
          <div className={style.contentContainer}>
            <p>
              The next VIzon draw is on {nextUpcomingDate.format('dddd')}, {nextUpcomingDate.format('L LT')}.
            </p>
            <Countdown date={nextUpcomingDate} />
          </div>
        </div>
      </div>
    );
  }
}

export default App;
