import React, { Component } from 'react';
import dateformat from 'dateformat';

import DayPicker, { DateUtils } from 'react-day-picker';
import { daypickerLocale } from 'cem/localization';

const restricters = {
  past: DateUtils.isPastDay,
  future: (day) => (!DateUtils.isSameDay(day, new Date()) && !DateUtils.isPastDay(day)),
};

export default () => {
  return class extends Component {
    constructor() {
      super();

      this.state = {
        active: false,
      };
      this.clickOutside = ::this.clickOutside;
    }

    componentDidUpdate(prevProps, prevStates) {
      if (prevStates.active === this.state.active) {
        return;
      }

      if (this.state.active) {
        document.addEventListener(`click`, this.clickOutside);
      } else {
        document.removeEventListener(`click`, this.clickOutside);
      }
    }

    toggle() {
      this.setState({ active: !this.state.active});
    }

    clickOutside(event) {
      if (this.state.active && !this.refs.daypicker.contains(event.target)) {
        this.setState({
          active: !this.state.active,
        });
      }
    }

    handleDayClick(e, day, modifiers) {
      if (modifiers.indexOf(`disabled`) === -1) {
        this.props.onDayClick(day);
        this.toggle();
      }
    }

    render() {
      const controlProps = this.props.control.props;
      const initialValue = controlProps.value;
      const value = initialValue ? dateformat(initialValue, `dd.mm.yyyy`) : ``;

      const modifiers = {
        selected: (day) => DateUtils.isSameDay((new Date(initialValue)), day),
        disabled: this.props.restrict ? restricters[this.props.restrict] : () => false,
      };

      return (
        <div ref="daypicker" className={this.props.className}>
          {React.cloneElement(this.props.control, { disabled: true, value })}
          {React.cloneElement(this.props.button, { onClick: ::this.toggle, type: `button` })}
          {this.props.close && this.props.close}
          {this.state.active && <DayPicker locale="ru" localeUtils={daypickerLocale} modifiers={modifiers} onDayClick={::this.handleDayClick} />}
        </div>
      );
    }
  };
};
