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

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

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

  constructor(props: DatePickerProps) {
    super(props);
    this.defaultOptions = {
      autoClose: true,
      format: 'DD.MM.YYYY',
      language: 'ru',
      separator: ' - ',
      singleDate: true,
      singleMonth: true,
      showShortcuts: false,
      showTopbar: false,
      stickyMonths: true,
      startOfWeek: 'monday',
    };
    this.state = {
      options: { ...this.defaultOptions, ...props.options },
    };
  }

  defaultOptions: Object

  dateRef: ?HTMLElement

  componentDidMount() {
    this.setState({ value: this.getValue() });
    $(this.dateRef).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.dateRef).data('dateRangePicker').destroy();
      $(this.dateRef).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 false;
    }
  }

  getValue() {
    /* if(this.props.value){
      let value = this.getDate(this.props.value);
      return `${value}`;
    }
    return ''; */
    return this.props.value ? this.getDate(this.props.value) : '';
  }

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