import React, { PropTypes } from 'react';
import options, { defaultOptions } from './options';
import Datepicker from 'react-datepicker';
import moment from 'moment';

import BetweenDatepicker from './BetweenDatepicker';
import BaseSelect from '../BaseSelect';
import wrap from '../ItemContainerWrapper';

const defaultProps = {
  min: moment().subtract(3, 'months'),
  max: moment().add(1, 'years'),
};
const propTypes = {
  min: PropTypes.object,
  max: PropTypes.object,
  onOptionSelected: PropTypes.func,
  onItemAdded: PropTypes.func,
};

class KdSelectDate extends React.Component
{
  constructor(props) {
    super(props);

    this.options = defaultOptions.map(option => options.create(option));
    this.state = { selectedOption: this.options[0] };

    this.handleChange = this.handleChange.bind(this);
    this.onSelectChange = this.onSelectChange.bind(this);
  }

  componentWillMount() {
    this.props.onOptionSelected(this.state.selectedOption.id);
  }

  handleChange(date) {
    const involvedOption = this.options.find(option => this.state.selectedOption.id === option.id);
    involvedOption.selected = date;

    this.props.onItemAdded(involvedOption.selected);
  }

  selectedOptionHelper() {
    const { selectedOption } = this.state;
    const { min, max } = this.props;
    switch (selectedOption.id) {
      case 'after':
      case 'before':
        return (
          <Datepicker
            selected={selectedOption.selectedValue || moment()}
            onChange={this.handleChange}
            showMonthDropdown
            dropdownMode="select"
            showYearDropdown
            minDate={min}
            maxDate={max}
            scrollableYearDropdown
          />
        );
      case 'between':
        return (
          <BetweenDatepicker
            onChange={this.handleChange}
            min={min}
            max={max}
          />
        );
      default:
        return null;
    }
  }

  onSelectChange({ target }) {
    const selectedOption = this.options.find(option => option.id === target.value);

    if (selectedOption.loadDefaultValue()) {
      this.props.onItemAdded(selectedOption.selected);
    }

    this.props.onOptionSelected(selectedOption.id);

    this.setState({ selectedOption });
  }

  render() {
    return (
      <div>
        <BaseSelect inline options={this.options} onChange={this.onSelectChange} />
        {this.selectedOptionHelper()}
      </div>
    );
  }
}

KdSelectDate.defaultProps = defaultProps;
KdSelectDate.propTypes = propTypes;

export default wrap(KdSelectDate);
