import React from 'react';
import moment from 'moment-timezone';
import PropTypes from 'prop-types';
import DigitBlock from './DigitBlock';
import ProgressCircle from './ProgressCircle';

import style from './Countdown.sass';

export default class Countdown extends React.Component {
  static propTypes = {
    date: PropTypes.object.isRequired,
    locale: PropTypes.string,
    minimumIntegerDigits: PropTypes.number,
    useGrouping: PropTypes.bool,
    getNow: PropTypes.func,
  };

  static defaultProps = {
    locale: undefined,
    minimumIntegerDigits: 2,
    useGrouping: false,
    getNow: () => moment(),
  }

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

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

  calculateDiff() {
    const { getNow, date } = this.props;
    return date.diff(getNow());
  }

  tick() {
    this.setState({ duration: this.calculateDiff() });
  }

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

    const { duration } = this.state;

    const durationMoment = moment.duration(duration);

    const days = durationMoment.days();
    const hours = durationMoment.hours();
    const minutes = durationMoment.minutes();
    const seconds = durationMoment.seconds();

    const size = 160; // @HACK

    const { locale, minimumIntegerDigits, useGrouping } = this.props;
    return (
      <div className={style.countdown}>
        <ProgressCircle size={size} max={3} progress={days} stroke="rgb(60, 90, 128)">
          <DigitBlock suffix="d">
            {days.toLocaleString(locale, {
              minimumIntegerDigits,
              useGrouping,
            })}
          </DigitBlock>
        </ProgressCircle>
        <ProgressCircle size={size} max={24} progress={hours} stroke="rgb(60, 144, 60)">
          <DigitBlock suffix="h">
            {hours.toLocaleString(locale, {
              minimumIntegerDigits,
              useGrouping,
            })}
          </DigitBlock>
        </ProgressCircle>
        <ProgressCircle size={size} max={60} progress={minutes} stroke="rgb(160, 154, 40)">
          <DigitBlock suffix="m">
            {minutes.toLocaleString(locale, {
              minimumIntegerDigits,
              useGrouping,
            })}
          </DigitBlock>
        </ProgressCircle>
        <ProgressCircle size={size} max={60} progress={seconds} stroke="rgb(155, 50, 70)">
          <DigitBlock suffix="s">
            {durationMoment.seconds().toLocaleString(locale, {
              minimumIntegerDigits,
              useGrouping,
            })}
          </DigitBlock>
        </ProgressCircle>
      </div>
    );
  }
}
