// @flow
import React from 'react';
import $ from 'jquery';
import moment from 'moment';
import './jquery.daterangepicker';
// import './scss/daterangepicker.scss';

/** Props, передаваемые в DateTimeRangePicker
  * @property {object} options - опции для доп. настройки, описание есть по ссылке
  *    https://longbill.github.io/jquery-date-range-picker/#configuration
  * @property {Function} onChange - коллбэк принимающий объект с результатом выбора.
  *    Объект следующей структуры:
  *  {
  *    date1: (Date object of the earlier date),
  *    date2: (Date object of the later date),
  *    value: "2013-06-05 to 2013-06-07"
  *  }
  * @property {Object} value - дефолтные даты, отображающиеся при загрузке компонента.
  * передаются в формате { start: any, end: any }, start и end могут быть строкой, timestamp
  * или объектом moment.
*/
type DateTimeRangePickerProps = {
  options?: { [string]: any },
  onChange: Function,
  value: { start: any, end: any },
};
type DateTimeRangePickerState = {
  options: { [string]: any },
};

/** Компонент DateTimeRangePicker - рисует 2 календаря и дает возможность выбора диапазона дат
  * с указанием времени начальной даты и конечной
  */
export default class DateTimeRangePicker extends React.Component<DateTimeRangePickerProps,DateTimeRangePickerState> {
  static defaultProps = {
    onChange: () => null,
  }

  constructor(props: DateTimeRangePickerProps) {
    super(props);
    this.defaultOptions = {
      autoClose: false,
      format: 'DD.MM.YYYY HH:mm',
      language: 'ru',
      separator: ' - ',
      showShortcuts: false,
      time: {
        enabled: true,
      },
      defaultTime: moment().startOf('day').toDate(),
      defaultEndTime: moment().endOf('day').toDate(),
      showTopbar: false,
      stickyMonths: true,
      startOfWeek: 'monday',
    };
    this.state = {
      options: { ...this.defaultOptions, ...props.options },
    };
  }

  defaultOptions: Object

  dateTimeRef: ?HTMLElement

  componentDidMount() {
    this.setState({ value: this.getValue() });
    $(this.dateTimeRef).dateRangePicker(this.state.options)
      .bind('datepicker-change', (event, result: Object) => {
        this.props.onChange(result);
      });
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.value && (this.props.value !== prevProps.value)) {
      this.setState({ value: this.getValue() });
    }
    if (this.props.options !== prevProps.options) {
      this.setState({ options: { ...this.defaultOptions, ...this.props.options } });
    }
    /* if (this.state.options !== prevState.options) {
      $(this.dateTimeRef).data('dateRangePicker').destroy();
      $(this.dateTimeRef).dateRangePicker(this.state.options)
        .bind('datepicker-change', (event, result: Object) => {
          this.props.onChange(result);
        });
    } */
  }

   getDate(date: any) {

    let type = typeof(date);

    switch(type){

      case 'string':
        return date;

      case 'number':
        return moment(date, 'X').format(this.state.options.format);

      case 'object':
        if(moment.isMoment(date))
          return moment(date).format(this.state.options.format);

      default:
        return '';
    }
  }

  getValue() {
    if(this.props.value && this.props.value.start && this.props.value.end){

      let start = this.getDate(this.props.value.start),
          end = this.getDate(this.props.value.end);

      return `${start}${this.state.options.separator}${end}`;
    }
    return '';
  }

  render() {
    const { value } = this.state;
    // eslint-disable-next-line no-return-assign
    return <input className='omni-ui-general omni-datetime-range-picker' defaultValue={value} ref={ref => this.dateTimeRef = ref}/>;
  }
}
